Để tìm tài liệu bằng cách không tồn tại trường trong MongoDB, cú pháp như sau -
db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty(); Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> 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")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -
> db.findDocumentNonExistenceFieldDemo.find().pretty();
Sau đây là kết quả -
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
"StudentName" : "David",
"StudentAge" : 26,
"StudentMathMarks" : 78
} Đây là truy vấn để tìm tài liệu theo sự không tồn tại của trường -
> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty(); Sau đây là kết quả -
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}