Truy vấn và projection trường lồng nhau với dot notation
Khi document chứa object con, dùng dot notation object.trường trong cả filter và projection.
Dữ liệu tên đầy đủ
> db.demo361.insertOne({ "details": { "FirstName": "Chris", "LastName": "Brown" } });
> db.demo361.insertOne({ "details": { "FirstName": "David", "LastName": "Miller" } });
> db.demo361.insertOne({ "details": { "FirstName": "John", "LastName": "Doe" } });
Chỉ lấy LastName (projection)
> db.demo361.find({}, { "details.LastName": 1 });
Kết quả
{ "_id": ..., "details": { "LastName": "Brown" } }
{ "_id": ..., "details": { "LastName": "Miller" } }
{ "_id": ..., "details": { "LastName": "Doe" } }
Truy vấn lọc: db.demo361.find({ "details.FirstName": "David" })
Mẹo: Projection { "details.LastName": 1 } giữ nguyên cấu trúc object details nhưng chỉ chứa LastName. Dùng { "details.LastName": 1, _id: 0 } để loại _id.