Để tìm tài liệu mà phần tử mảng không có trường cụ thể, sử dụng toán tử $elemMatch. Toán tử này khớp với tài liệu chứa mảng có ít nhất một phần tử thỏa mãn tất cả tiêu chí truy vấn.
Tạo collection với mảng lồng nhau:
> db.demo239.insertOne({
... "Name" : "Chris",
... "details" : [
... { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 },
... { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 }
... ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e441c6bf4cebbeaebec5157") }
> db.demo239.insertOne({
... "Name" : "David",
... "details" : [
... { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450},
... { "DueDate" : new ISODate("2020-02-12") }
... ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e441c6cf4cebbeaebec5158") }
Hiển thị dữ liệu (lưu ý bản ghi thứ 2 thiếu ProductPrice ở phần tử thứ 2):
> db.demo239.find();
{ "_id" : ObjectId("5e441c6bf4cebbeaebec5157"), "Name" : "Chris", "details" : [
{ "DueDate" : ISODate("2019-01-21T00:00:00Z"), "ProductPrice" : 1270 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z"), "ProductPrice" : 2000 }
] }
{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
{ "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z") }
] }
Truy vấn tìm tài liệu có phần tử mảng có DueDate nhưng KHÔNG có ProductPrice:
> db.demo239.find({
"details": {
"$elemMatch": {
"DueDate": { "$exists": true },
"ProductPrice": { "$exists": false }
}
}
})
Kết quả trả về tài liệu của David (có phần tử thiếu ProductPrice):
{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
{ "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z") }
] }