Để tìm document theo sự không tồn tại của một trường trong MongoDB, bạn sử dụng toán tử $exists với giá trị false.
Cú pháp
db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty();
Ví dụ minh họa
Tạo collection và dữ liệu
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"John","StudentAge":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a5c629064dcd4a68b70e8") }
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"David","StudentAge":26,"StudentMathMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a5c809064dcd4a68b70e9") }
Xem tất cả documents
> db.findDocumentNonExistenceFieldDemo.find().pretty();
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
"StudentName" : "David",
"StudentAge" : 26,
"StudentMathMarks" : 78
}
Tìm document không có trường StudentMathMarks
> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty();
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
Kết quả chỉ trả về document của John vì document này không có trường StudentMathMarks.
Lưu ý
{ "$exists" : true }- tìm document có trường{ "$exists" : false }- tìm document không có trường- Toán tử này khác với kiểm tra giá trị
null- trường có thể tồn tại nhưng giá trị là null