首页 文章

检查字段是否存在于MongoDB中

提问于
浏览
96

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

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

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

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

db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })

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

4 回答

  • 134

    使用 $ne (适用于"not equal")

    db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
    
  • 2

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

    { 
      "_id":"1234"
      "open":"Yes"
      "things":{
                 "paper":1234
                 "bottle":"Available"
                 "bottle_count":40
                } 
    }
    

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

    答:

    db.products.find({"things.bottle":{"$exists":true}})
    
  • -1

    我发现这适合我

    db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
    
  • 19

    你可以用 .Count()

    count, err = collection.Find(bson.M{field: value}).Count()
    

    但请记住设置:

    Session.SetSafe

    db.SetSafe(&mgo.Safe{})
    

    否则每次通话都会返回0 .

相关问题