如何在 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" }
广告