MongoDB:如何查询字段为空或未设置的记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10591543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:39:46  来源:igfitidea点击:

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

mongodbnullmongodb-queryexists

提问by Andrew

I have an Emaildocument which has a sent_atdate field:

我有一个Email包含sent_at日期字段的文档:

{
  'sent_at': Date( 1336776254000 )
}

If this Emailhas not been sent, the sent_atfield is either null, or non-existant.

如果Email尚未发送,则该sent_at字段为空或不存在。

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:

我需要获取所有已发送/未发送的计数Emails。我一直在试图找出查询此信息的正确方法。我认为这是获取发送计数的正确方法:

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

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

但是我应该如何获得未发送的数量?

回答by jdi

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

如果 sent_at 字段在未设置时不存在,则:

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

请参阅此处进行查询和 null

回答by tvs

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

如果您只想计算sent_at定义为值null的文档(不要计算sent_at未设置的文档):

db.emails.count({sent_at: { $type: 10 }})

回答by Anil Tallam

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.

计算其 sent_at 属性为空或未设置的所有电子邮件。上面的查询与下面的相同。

db.emails.count($or: [
  {sent_at: {$exists: false}},
  {sent_at: null}
])

回答by Jim Horng

Seems you can just do single line:

似乎你只能做单行:

{ "sent_at": null }

回答by Vivek Maraina

You can also try this:

你也可以试试这个:

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