MongoDB: How to query for records where field is null or not set?

前端 未结 6 1900
鱼传尺愫
鱼传尺愫 2020-11-27 12:58

I have an Email document which has a sent_at date field:

{
  \'sent_at\': Date( 1336776254000 )
}

If this E

相关标签:
6条回答
  • 2020-11-27 13:38

    Use:

    db.emails.count({sent_at: null})
    

    Which counts all emails whose sent_at property is null or is not set. The above query is same as below.

    db.emails.count($or: [
      {sent_at: {$exists: false}},
      {sent_at: null}
    ])
    
    0 讨论(0)
  • 2020-11-27 13:40

    You can also try this:

    db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
    
    0 讨论(0)
  • 2020-11-27 13:51

    If you want to ONLY count the documents with sent_at defined with a value of null (don't count the documents with sent_at not set):

    db.emails.count({sent_at: { $type: 10 }})
    
    0 讨论(0)
  • 2020-11-27 13:51
    db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();
    
    0 讨论(0)
  • 2020-11-27 13:54

    Seems you can just do single line:

    { "sent_at": null }
    
    0 讨论(0)
  • 2020-11-27 13:58

    If the sent_at field is not there when its not set then:

    db.emails.count({sent_at: {$exists: false}})
    

    If its there and null, or not there at all:

    db.emails.count({sent_at: null})
    

    Refer here for querying and null

    0 讨论(0)
提交回复
热议问题