查找 MongoDB 中没有特定字段的项目?
要查找没有特定字段的项目,请使用 $exists 运算符。语法如下 -
> db.yourCollectionName.find({"yourItemName":{$exists:false}}).pretty();
为了理解语法,让我们用文档创建一个集合。使用文档创建集合的查询如下 -
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserId":101,"UserName":"John","UserAge":21});{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a95fb6cea1f28b7aa07fb")
}
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"David","UserAge":22,"UserFavouriteSubject":["C","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a96116cea1f28b7aa07fc")
}
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"Bob","UserAge":24,"UserFavouriteSubject":["MongoDB","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a96306cea1f28b7aa07fd")
}
在find()方法的帮助下显示集合中的所有文档。查询如下 -
> db.findDocumentDoNotHaveCertainFields.find().pretty();
以下是输出 -
{"_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"),
"UserId" : 101,
"UserName" : "John",
"UserAge" : 21
}
{
"_id" : ObjectId("5c8a96116cea1f28b7aa07fc"),
"UserName" : "David",
"UserAge" : 22,
"UserFavouriteSubject" : [
"C",
"Java"
]
}
{
"_id" : ObjectId("5c8a96306cea1f28b7aa07fd"),
"UserName" : "Bob",
"UserAge" : 24,
"UserFavouriteSubject" : [
"MongoDB",
"MySQL"
]
}
这是查找没有特定字段的项目的查询,即 UserFavouriteSubject -
> db.findDocumentDoNotHaveCertainFields.find({"UserFavouriteSubject":{$exists:false}}).pretty();
以下是输出 -
{"_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"),
"UserId" : 101,
"UserName" : "John",
"UserAge" : 21
}
以上是 查找 MongoDB 中没有特定字段的项目? 的全部内容, 来源链接: utcz.com/z/347593.html