检查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