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

问题描述 投票:0回答:10

我有一个

Email
文档,其中有
sent_at
日期字段:

{
  'sent_at': Date( 1336776254000 )
}

如果尚未发送此

Email
,则
sent_at
字段为空或不存在。

我需要获取所有已发送/未发送的计数

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

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

但是我该如何获取未发送的数量呢?

mongodb null mongodb-query exists
10个回答
265
投票

如果

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 Type Null
(类型编号 
10
):

db.inventory.find( { item : { $type: 10 } } )

    

22
投票
如果您只想计算

sent_at

 定义为 
null
 的文档(不要计算未设置 
sent_at
 的文档):

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

18
投票
用途:

db.emails.count({sent_at: null})
统计所有sent_at属性为null或未设置的电子邮件。
上面的查询与下面的相同。

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

10
投票
似乎你只能做单行:

{ "sent_at": null }
    

4
投票
以上所有答案都令人惊奇且正确。只是想对使用

$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
    


3
投票

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

以上可以在单行查询中完成,这将花费更少的时间-

db.emails.count($or: [ {sent_at: nil }])

因为除了值之外,如果键 
nil

也是

doesn't exist
null
也会获取文档。
最好看一下来源
它救了我的命。

注意:在较新版本的 mongodb 中,使用
nil

代替

null

    


1
投票

db.emails.find({"sent_at": {$in:[null,""]}).count()



0
投票

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



0
投票
sent_at

字段

为空或不存在的所有文档的计数,可以使用以下简短查询:
db.emails.count({ sent_at: { $not: { $ne: null } } })

说明:

使用

{ $ne: null }
    查询字段中
  1. 值的所有文档。
    在其上添加$not
  2. ,查询相反的内容:所有
  3. 在该字段中具有值的文档。
db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();

-1
投票

© www.soinside.com 2019 - 2024. All rights reserved.