检查字段是否存在于MongoDB中

Alb*_*elB 114 mongodb

所以我试图找到所有具有字段集且不为空的记录.

我尝试使用$exists,但根据MongoDB文档,此查询将返回等于null的字段.

$exists 匹配包含存储空值的字段的文档.

所以我现在假设我必须做这样的事情:

db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
Run Code Online (Sandbox Code Playgroud)

每当我尝试这个时,我得到错误[invalid use of $not] 任何人都知道如何查询这个?

Ser*_*sev 159

使用$ne("不等于")

db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
Run Code Online (Sandbox Code Playgroud)

  • @iLoveUnicorns:`find`总是返回:匹配条件的记录集合. (4认同)
  • @SergioTulentsev AFAIK 它返回一个游标 (4认同)

小智 21

假设我们有一个如下集合:

{ 
  "_id":"1234"
  "open":"Yes"
  "things":{
             "paper":1234
             "bottle":"Available"
             "bottle_count":40
            } 
}
Run Code Online (Sandbox Code Playgroud)

我们想知道瓶子领域是否存在?

答:

db.products.find({"things.bottle":{"$exists":true}})
Run Code Online (Sandbox Code Playgroud)

  • `当<boolean>为true时,$ exists匹配包含该字段的文档,包括字段值为null的文档.[来自文档.](http://docs.mongodb.org/manual/reference/operator /查询/存在/) (2认同)

Yak*_*nor 5

我发现这对我有用

db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
Run Code Online (Sandbox Code Playgroud)