Để truy xuất trường con bên trong đối tượng nhúng, dùng ký hiệu chấm (dot notation) trong projection.
Cú pháp:
db.yourCollectionName.find({}, {'yourOuterKey.yourInnerKey': 1}).pretty();
Ví dụ: Collection embeddedCollectionDemo có trường StudentDetails là đối tượng nhúng:
> db.embeddedCollectionDemo.insertOne({
"StudentName": "Larry",
"StudentDetails": {
"Larry1234": {"ProjectName": "Student Web Tracker"},
"Larry7645": {"ProjectName": "Hospital Management System"},
"Larry9879": {"ProjectName": "Library Management System"}
}
});
Xem toàn bộ tài liệu:
> db.embeddedCollectionDemo.find().pretty();
Truy xuất chỉ ProjectName của Larry7645:
> db.embeddedCollectionDemo.find({}, {'StudentDetails.Larry7645': 1}).pretty();
Kết quả:
{ "_id" : ObjectId(...), "StudentDetails" : { "Larry7645" : { "ProjectName" : "Hospital Management System" } } }
Lưu ý: Projection {'field': 1} chỉ trả về trường đó (và _id mặc định). Dùng {_id: 0} để loại bỏ _id nếu không cần.