如何检查MongoDB中是否存在字段?
要检查MongoDB中是否存在字段,可以使用$exists运算符。
为了理解上述概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba4136de59bd9de063a1")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba4e36de59bd9de063a2")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba6536de59bd9de063a3")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"UK","StudentHobby":["Teaching","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92ba9d36de59bd9de063a4")
}在find()method的帮助下显示集合中的所有文档。查询如下-
> db.checkFieldExistsOrNotDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c92ba4136de59bd9de063a1"), "StudentName" : "Larry" }
{
"_id" : ObjectId("5c92ba4e36de59bd9de063a2"),
"StudentName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c92ba6536de59bd9de063a3"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
"StudentName" : "Robert",
"StudentAge" : 21,
"StudentCountryName" : "UK",
"StudentHobby" : [
"Teaching",
"Photography"
]
}这是检查MongoDB中是否存在字段的查询。
情况1-当字段存在时。
查询如下-
> db.checkFieldExistsOrNotDemo.find({ 'StudentHobby' : { '$exists' : true }}).pretty();以下是输出-
{
"_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
"StudentName" : "Robert",
"StudentAge" : 21,
"StudentCountryName" : "UK",
"StudentHobby" : [
"Teaching",
"Photography"
]
}情况2-字段不存在时。
查询如下:
> db.checkFieldExistsOrNotDemo.find({ 'StudentTechnicalSubject' : { '$exists' : true }}).pretty();当字段不存在时,您将不会获得任何东西。