Sử dụng $match kết hợp $and trong aggregation để lọc tài liệu thỏa mãn nhiều điều kiện cùng lúc. Tạo collection lồng sâu:
> db.demo574.insertOne({
... "details1": {
... "details2": {
... "dueDate": new ISODate("2020-01-10"),
... "Name": "Chris",
... "UserInformation": { "Name": "John", "Marks": 78 },
... "CountryName": "US"
... },
... "id":101
... }
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e9167f3581e9acd78b427f6") }
Hiển thị dữ liệu:
> db.demo574.find();
{ "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" : { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" : { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 } }
Aggregation với $match + $and (3 điều kiện):
> db.demo574.aggregate({
... $match: {
... $and: [
... {"details1.id": 101},
... {"details1.details2.UserInformation.Name": 'John'},
... {"details1.details2.Name": 'Chris'}
... ]
... }
... });
Kết quả (khớp tất cả 3 điều kiện):
{ "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" : { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" : { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 } }
Lưu ý: Trong $match, các điều kiện cùng cấp mặc định là AND. $and chỉ cần thiết khi cùng một trường xuất hiện nhiều lần hoặc để rõ ràng logic.