MongoDB查询以获取没有特定字段的文档?
要检查是否存在,请使用$exists。让我们创建一个包含文档的集合-
> db.demo234.insertOne({"FirstName":"Chris","LastName":"Brown","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a50f4cebbeaebec5148") } > db.demo234.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a5ff4cebbeaebec5149") } > db.demo234.insertOne({"FirstName":"John","LastName":"Smith",Age:34}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a70f4cebbeaebec514a") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo234.find();
这将产生以下输出-
{ "_id" : ObjectId("5e418a50f4cebbeaebec5148"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 } { "_id" : ObjectId("5e418a5ff4cebbeaebec5149"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e418a70f4cebbeaebec514a"), "FirstName" : "John", "LastName" : "Smith", "Age" : 34 }
以下是检查是否存在并获取没有“年龄”字段的文档的查询-
> var iterator = db.demo234.find({"Age":{$exists:false}},{"_id":0}); > iterator.forEach(function(d) ...{ ... printjson(d); ...})
这将产生以下输出-
{ "FirstName" : "David", "LastName" : "Miller" }