我有一个包含日期字段的Email文档:sent_at
{
'sent_at': Date( 1336776254000 )
}
如果Email尚未发送,则该sent_at字段为空或不存在。
我需要获取所有已发送/未发送的计数Emails。我一直在试图找出查询这些信息的正确方法。我认为这是获取发送计数的正确方法:
db.emails.count({sent_at: {$ne: null}})
但是我应该如何计算未发送的数量?
我有一个包含日期字段的Email文档:sent_at
{
'sent_at': Date( 1336776254000 )
}
如果Email尚未发送,则该sent_at字段为空或不存在。
我需要获取所有已发送/未发送的计数Emails。我一直在试图找出查询这些信息的正确方法。我认为这是获取发送计数的正确方法:
db.emails.count({sent_at: {$ne: null}})
但是我应该如何计算未发送的数量?
如果该sent_at字段在未设置时不存在,则:
db.emails.count({sent_at: {$exists: false}})
如果它存在并且为空,或者根本不存在:
db.emails.count({sent_at: null})
如果它在那里并且为空:
db.emails.count({sent_at: { $type: 10 }})
MongoDB 手册的Query for Null or Missing Fields部分描述了如何查询空值和缺失值。
平等过滤器
该
{ item : null }查询匹配包含其值为null或不包含该item字段的 item 字段的文档。db.inventory.find( { item: null } )
存在检查
以下示例查询不包含字段的文档。
{ item : { $exists: false } }查询匹配不包含该item字段的文档:db.inventory.find( { item : { $exists: false } } )
类型检查
该查询仅
{ item : { $type: 10 } }匹配包含值为;的字段的文档。即项目字段的值是BSON 类型(类型号):itemnullNull10db.inventory.find( { item : { $type: 10 } } )
如果您只想计算sent_at值定义为的文档null(不要计算sent_at未设置的文档):
db.emails.count({sent_at: { $type: 10 }})
利用:
db.emails.count({sent_at: null})
它计算所有 sent_at 属性为 null 或未设置的电子邮件。上面的查询与下面的相同。
db.emails.count($or: [
{sent_at: {$exists: false}},
{sent_at: null}
])
似乎你可以只做单行:
{ "sent_at": null }
以上所有答案都是惊人的和正确的。只想对正在使用的答案添加一项改进$type。
从 MongoDB 3.2 开始,您可以避免使用10(因为硬编码文字会降低代码的可读性),而是可以简单地使用字符串别名,即"null". 所以总结一下——
sent_at存在且具有价值的记录nulldb.emails.count({sent_at: { $type: 'null' }});
// or
// This reduces the code readability as your peer might not know
// that what is the meaning of value 10
db.emails.count({sent_at: { $type: 10 }});
sent_at: null或sent_at不存在的记录// This will ensure both the conditions
db.emails.count({ sent_at: null })
sent_at存在的记录db.emails.count({sent_at: { $exists: false }});
sent_at字段存在的位置并且可能有任何值db.emails.count({sent_at: { $exists: true }});
请记住,这将拉取任何emails具有任何价值的文档,包括null, 0, '', false。
你也可以试试这个:
db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
您可以使用 $in 运算符来检查这两种情况
db.emails.find({"sent_at": {$in:[null,""]}).count()
如果需要在同一文档中检查属性和值是否存在等于 null -
db.emails.count($or: [
{sent_at: {$exists: false}},
{sent_at: null}
])
以上可以在单行查询中完成,这将花费更少的时间,因为-
db.emails.count($or: [ {sent_at: nil }])
因为nil如果doesn't exist除了 value 之外的 key 也是null.
最好看一下它节省了我一天的来源。
注意:在较新版本的 mongodb 中使用
nil,而不是。null
db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();