Để truy vấn bên trong mảng đối tượng (subdocument), MongoDB hỗ trợ dot notation (ký hiệu dấu chấm) để truy cập trường lồng nhau.
Tạo collection với mảng subdocument
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Carol","StudentSubject":"Java"},{ "StudentName" : "David", "StudentSubject" : "MongoDB" }]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf6ec71bf0181ecc4229d") }
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Mike","StudentSubject":"Python"},{ "StudentName" : "David", "StudentSubject" : "C" }]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf70471bf0181ecc4229e") }
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Jace","StudentSubject":"C++"},{ "StudentName" : "John", "StudentSubject" : "MySQL" }]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf72071bf0181ecc4229f") }
Truy vấn với dot notation
Tìm document có bất kỳ phần tử nào trong StudentDetails có StudentSubject="MongoDB":
> db.demo81.find({"StudentDetails.StudentSubject":"MongoDB"});
Kết quả
{ "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentSubject" : "Java" }, { "StudentName" : "David", "StudentSubject" : "MongoDB" } ] }
Điểm quan trọng:
- Dot notation
"StudentDetails.StudentSubject"khớp nếu ít nhất một phần tử trong mảng thỏa mãn - Trả về toàn bộ document (kể cả các phần tử không khớp trong mảng)
- Chỉ dùng được cho truy vấn đọc (find), không dùng cho update điểm chính xác một phần tử (cần
$positional operator hoặc$elemMatch) - Để chỉ trả về phần tử khớp, dùng projection với
$elemMatchhoặc aggregate$filter