MongoDB cho phép chỉ định các trường cần trả về (projection) trong phương thức find(). Sử dụng dot notation để truy cập các trường lồng nhau trong tài liệu nhúng.
Dữ liệu mẫu
> db.demo307.insertOne({ "CleintId":101, "ClientDetails":{"ClientFirstName":"Chris","Age":34}, "ClientCountryName":"US" });
{ "acknowledged" : true, "insertedId" : ObjectId("5e4eab88f8647eb59e56203c") }
> db.demo307.insertOne({ "CleintId":102, "ClientDetails":{"ClientFirstName":"David","Age":31}, "ClientCountryName":"UK" });
{ "acknowledged" : true, "insertedId" : ObjectId("5e4eab97f8647eb59e56203d") }
Xem tất cả trường
> db.demo307.find();
{ "_id" : ObjectId("5e4eab88f8647eb59e56203c"), "CleintId" : 101, "ClientDetails" : { "ClientFirstName" : "Chris", "Age" : 34 }, "ClientCountryName" : "US" }
{ "_id" : ObjectId("5e4eab97f8647eb59e56203d"), "CleintId" : 102, "ClientDetails" : { "ClientFirstName" : "David", "Age" : 31 }, "ClientCountryName" : "UK" }
Truy xuất chỉ trường ClientFirstName của David
Sử dụng projection (đối số thứ 2 của find) với giá trị 0 để loại trừ các trường không cần thiết, và dot notation "ClientDetails.ClientFirstName" trong bộ lọc (đối số thứ 1).
> db.demo307.find( {"ClientDetails.ClientFirstName":'David'}, {"ClientDetails.Age" : 0,"ClientCountryName":0,"CleintId":0,"_id":0});
Kết quả
{ "ClientDetails" : { "ClientFirstName" : "David" } }
Lưu ý: Không thể trộn lẫn inclusion (1) và exclusion (0) trong cùng một projection, trừ trường _id (mặc định inclusion, có thể set 0 để ẩn). Ví dụ trên dùng exclusion để ẩn các trường không cần.