Sử dụng dot notation để trích xuất phần tử từ mảng lồng nhiều cấp. Tạo collection:
> db.extractParticularElementDemo.insertOne(
{
"_id" : 101,
"StudentName" : "John",
"StudentInformation" : [
{
"Age" : 21,
"StudentPersonalInformation" : [
{
"StudentNickName" : "Mike",
"StudentFamilyDetails" : [
{ "FatherName" : "Carol" }
]
},
{
"StudentAnotherName" : "David",
"StudentFamilyDetails" : [
{ "FatherName" : "Robert" }
]
}
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 101 }
Hiển thị tài liệu đầy đủ:
> db.extractParticularElementDemo.find().pretty();
Truy vấn tìm FatherName="Carol" và projection chỉ trả về trường đó:
> db.extractParticularElementDemo.find( {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName': 'Carol'}, {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName': 1, "_id": 0} ).pretty();Kết quả - trả về toàn bộ đường dẫn chứa "Carol" (MongoDB projection trên mảng lồng nhau trả về tất cả phần tử cùng đường dẫn):
Lưu ý: Projection trên mảng lồng nhau không lọc được phần tử con, chỉ include/exclude đường dẫn. Để lọc chính xác phần tử, dùng aggregation với
$unwindvà$match.