Khi cần tìm tài liệu mà ít nhất một phần tử trong mảng thoả mãn nhiều điều kiện cùng lúc, hãy dùng $elemMatch. Khác với dot notation đơn giản (khớp nếu các điều kiện phân tán trên nhiều phần tử), $elemMatch yêu cầu tất cả điều kiện phải đúng trên cùng một phần tử.
Dữ liệu mẫu
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Chris","ClientProject":"Online Banking System"},{"ClientName":"David","ClientProject":"Online School Management"}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e351957fdf09dd6d08539df") }
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Carol","ClientProject":"Online Book System"},{"ClientName":"Mike","ClientProject":"Game Development"}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0") }
Xem dữ liệu
> db.demo153.find();
{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }
{ "_id" : ObjectId("5e3519c9fdf09dd6d08539e0"), "ClientDetails" : [ { "ClientName" : "Carol", "ClientProject" : "Online Book System" }, { "ClientName" : "Mike", "ClientProject" : "Game Development" } ] }
Truy vấn: Tìm tài liệu có phần tử ClientProject = "Online Banking System"
> db.demo153.find({"ClientDetails": { "$elemMatch" : {"ClientProject": { "$in": ["Online Banking System"] } } } });
Kết quả
{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }
So sánh: Nếu dùng dot notation {"ClientDetails.ClientProject": "Online Banking System"} kết quả giống nhau vì chỉ có một điều kiện. Nhưng nếu tìm ClientName="Chris" AND ClientProject="Online Banking System", $elemMatch bắt buộc cả hai phải trên cùng một phần tử, trong khi dot notation có thể khớp Chris ở phần tử 1 và Project ở phần tử 2.