如何确定MongoDB中是否存在字段?
您需要使用$exists运算符来确定MongoDB中是否存在字段。首先让我们创建一个包含文档的集合
> db.determineFieldExistsDemo.insertOne({"ClientName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb245d628fa4220163b75") } > db.determineFieldExistsDemo.insertOne({"ClientName":"Larry","ClientAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb25cd628fa4220163b76") } > db.determineFieldExistsDemo.insertOne({"ClientName":"Mike","ClientCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb26fd628fa4220163b77") } > db.determineFieldExistsDemo.insertOne({"ClientName":"Sam","ClientAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb286d628fa4220163b78") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.determineFieldExistsDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9eb245d628fa4220163b75"), "ClientName" : "John" } { "_id" : ObjectId("5c9eb25cd628fa4220163b76"), "ClientName" : "Larry", "ClientAge" : 23 } { "_id" : ObjectId("5c9eb26fd628fa4220163b77"), "ClientName" : "Mike", "ClientCountryName" : "UK" } { "_id" : ObjectId("5c9eb286d628fa4220163b78"), "ClientName" : "Sam", "ClientAge" : 24 }
以下是查询以确定是否存在字段
> db.determineFieldExistsDemo.find({ClientCountryName:{$exists:true}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9eb26fd628fa4220163b77"), "ClientName" : "Mike", "ClientCountryName" : "UK" }