Tìm tài liệu mà TẤT CẢ phần tử trong mảng đều có isRegular="Active". Tạo collection:
> db.demo74.insertOne({
StudentName: "Chris",
StudentDetails: [
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "InActive" },
{ "Subject": "MongoDB", "isRegular": "InActive" }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29c6b671bf0181ecc4226f") }
> db.demo74.insertOne({
name: "document2",
data: [
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "Active" }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29c6b771bf0181ecc42270") }
Hiển thị tài liệu:
> db.demo74.find();
Truy vấn: KHÔNG có phần tử nào isRegular != "Active" VÀ có ít nhất 1 phần tử isRegular = "Active":
> db.demo74.find({ "StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "StudentDetails.isRegular": "Active" }).pretty();Kết quả - tài liệu 1 (Chris) KHÔNG khớp vì có InActive. Tài liệu 2 (document2) KHÔNG khớp vì tên trường khác (data vs StudentDetails).
Sửa đúng cho tài liệu 2:
> db.demo74.find({ "data": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "data.isRegular": "Active" }).pretty();Giải thích:
$not + $elemMatch + $ne= "không tồn tại phần tử nào khác Active". Điều kiện thứ 2 đảm bảo mảng không rỗng và có ít nhất 1 "Active".