在 MongoDB 中查找没有某个字段的条目?
要查找没有某个字段的条目,请使用 $exists 运算符。语法如下 −
> db.yourCollectionName.find({"yourItemName":{$exists:false}}).pretty();
为理解语法,让我们通过文档创建一个集合。创建带文档的集合的查询如下 −
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserId":101,"UserName":"John","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a95fb6cea1f28b7aa07fb") } > db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"David","UserAge":22,"UserFavouriteSubject":["C","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a96116cea1f28b7aa07fc") } > db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"Bob","UserAge":24,"UserFavouriteSubject":["MongoDB","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a96306cea1f28b7aa07fd") }
借助 find() 方法从一个集合里展示所有文档。查询如下 −
> db.findDocumentDoNotHaveCertainFields.find().pretty();
输出如下 −
{ "_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"), "UserId" : 101, "UserName" : "John", "UserAge" : 21 } { "_id" : ObjectId("5c8a96116cea1f28b7aa07fc"), "UserName" : "David", "UserAge" : 22, "UserFavouriteSubject" : [ "C", "Java" ] } { "_id" : ObjectId("5c8a96306cea1f28b7aa07fd"), "UserName" : "Bob", "UserAge" : 24, "UserFavouriteSubject" : [ "MongoDB", "MySQL" ] }
这里有一个查询,它可以找到没有 UserFavouriteSubject 字段的条目 −
> db.findDocumentDoNotHaveCertainFields.find({"UserFavouriteSubject":{$exists:false}}).pretty();
输出如下 −
{ "_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"), "UserId" : 101, "UserName" : "John", "UserAge" : 21 }
广告