我有一个Email
文档,其中包含sent_at
日期字段:
{
'sent_at': Date( 1336776254000 )
}
如果尚未发送此Email
,则sent_at
字段为空或不存在。
我需要获取所有已发送/未发送Emails
的计数。我一直试图找出查询此信息的正确方法。我认为这是获得发送计数的正确方法:
db.emails.count({sent_at: {$ne: null}})
但是我该如何计算未发送的数?
答案 0 :(得分:159)
如果sent_at字段在未设置时不存在,则:
db.emails.count({sent_at: {$exists: false}})
如果它在那里并且为null,或者根本没有:
db.emails.count({sent_at: null})
答案 1 :(得分:12)
如果您只想计算sent_at
定义的值为null
的文档(不计算未设置sent_at
的文档):
db.emails.count({sent_at: { $type: 10 }})
答案 2 :(得分:10)
使用:
db.emails.count({sent_at: null})
对sent_at属性为null或未设置的所有电子邮件进行计数。 以上查询与以下内容相同。
db.emails.count($or: [
{sent_at: {$exists: false}},
{sent_at: null}
])
答案 3 :(得分:7)
似乎你可以单行:
{ "sent_at": null }
答案 4 :(得分:0)
您也可以尝试以下方法:
db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
答案 5 :(得分:0)
db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();
答案 6 :(得分:0)
您可以使用 $in 运算符来检查这两种情况
db.emails.find({"sent_at": {$in:[null,""]}).count()