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
MongoDB: How to query for records where field is null or not set?
提问by Andrew
I have an Email
document which has a sent_at
date field:
我有一个Email
包含sent_at
日期字段的文档:
{
'sent_at': Date( 1336776254000 )
}
If this Email
has not been sent, the sent_at
field 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})
回答by tvs
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):
如果您只想计算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()