检查 MongoDB 文档中字段是否存在值?
要检查 MongoDB 文档中字段是否存在值,可以使用 find() 和 $exists 运算符。我们先创建一个包含文档的集合 -
> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98") } > db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99") } > db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a") } > db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b") }
以下是使用 find() 方法从集合中显示所有文档的查询 -
> db.checkIfValueDemo.find().pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"), "PlayerName" : "John Smith", "PlayerScores" : [ 5000, 98595858, 554343 ] } { "_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"), "PlayerName" : "John Doe", "PlayerScores" : [ ] } { "_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"), "PlayerName" : "Carol Taylor", "PlayerScores" : [ 7848474, 8746345353 ] } { "_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"), "PlayerName" : "David Miller", "PlayerScores" : [ ] }
以下是检查文档中字段是否存在值的查询。此处,我们检查字段 'PlayerScores 具有值 [ ] -
> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count();
这将生成以下输出
2
广告