Dot notation trong projection của find() cho phép trích xuất trường lồng sâu trong object/array mà không cần aggregate.
Dữ liệu mẫu phức tạp
> db.demo235.insertOne({
"id":101,
"details":[
{ "Name":"Chris Brown", "Age":21 },
{ "Name":"David Miller", "Age":24 }
],
"otherdetails":[
{ "Score":56, "Subject":"MongoDB" },
{ "Score":78, "Subject":"MySQL" }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e418d22f4cebbeaebec514b") }
Truy vấn projection dot notation
> db.demo235.find({}, {"otherdetails.Subject":1, _id:0});
Kết quả
{ "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
Giải thích:
{"otherdetails.Subject":1}: Chỉ lấy trường Subject từ mỗi object trong mảng otherdetails- Giữ cấu trúc mảng, chỉ lọc trường con
_id:0: Tắt _id
So sánh:
| Phương pháp | Độ phức tạp | Linh hoạt | Hiệu suất |
|---|---|---|---|
| find() + dot notation | Thấp | Trung bình | Cao (dùng index) |
| aggregate $project | Trung bình | Cao | Cao |
| aggregate $map/$filter | Cao | Rất cao | Trung bình |
Chọn cách đơn giản nhất đáp ứng nhu cầu.