如何通过MongoDB中不存在的字段查找文档?
要通过MongoDB中不存在字段来查找文档,语法如下-
db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty();为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> 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")
}在find()method的帮助下显示集合中的所有文档。查询如下-
> db.findDocumentNonExistenceFieldDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
"StudentName" : "David",
"StudentAge" : 26,
"StudentMathMarks" : 78
}这是通过不存在字段来查找文档的查询-
> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty();以下是输出-
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}