我有一个
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 手册的查询空值或缺失字段部分描述了如何查询空值和缺失值。
平等过滤器
查询匹配包含值为{ item : null }
或 不包含null
字段的项目字段的文档。item
db.inventory.find( { item: null } )
存在性检查
以下示例查询不包含字段的文档。
查询匹配不包含{ item : { $exists: false } }
字段的文档:item
db.inventory.find( { item : { $exists: false } } )
类型检查
查询仅匹配包含值为{ item : { $type: 10 } }
item
的null
字段的文档;即项目字段的值是BSON TypeNull
(类型编号10
):db.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"
。总结一下-1.如果您想选择存在
sent_at
且值为
null
的记录
db.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 }});
2.如果您想选择具有 sent_at: null
或
sent_at
不存在的记录
// This will ensure both the conditions
db.emails.count({ sent_at: null })
3.如果您只想记录 sent_at
不存在的记录
db.emails.count({sent_at: { $exists: false }});
4.如果您只想选择字段存在且可能具有任何值的 sent_at
db.emails.count({sent_at: { $exists: true }});
请记住,这将拉取
emails
的任何具有任何值的文档,包括
null
、0
、''
、false
。db.emails.find({"sent_at": {$in:[null,""]}).count()
db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
sent_at
字段
为空或不存在的所有文档的计数,可以使用以下简短查询:
db.emails.count({ sent_at: { $not: { $ne: null } } })
说明:
使用
{ $ne: null }
值的所有文档。在其上添加
$not
在该字段中具有值的文档。
db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();