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

余生长醉 提交于 2019-11-26 07:24:20

问题


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

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

If this Email has not been sent, the sent_at field is either null, or non-existant.

I need to get the count of all sent/unsent Emails. I\'m stuck at trying to figure out the right way to query for this information. I think this is the right way to get the sent count:

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

But how should I get the count of the ones that aren\'t sent?


回答1:


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




回答2:


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 }})



回答3:


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}
])



回答4:


Seems you can just do single line:

{ "sent_at": null }



回答5:


You can also try this:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()


来源:https://stackoverflow.com/questions/10591543/mongodb-how-to-query-for-records-where-field-is-null-or-not-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!