121

我有一个包含日期字段的Email文档:sent_at

{
  'sent_at': Date( 1336776254000 )
}

如果Email尚未发送,则该sent_at字段为空或不存在。

我需要获取所有已发送/未发送的计数Emails。我一直在试图找出查询这些信息的正确方法。我认为这是获取发送计数的正确方法:

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

但是我应该如何计算未发送的数量?

4

9 回答 9

201

如果该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 类型(类型号):itemnull Null10

db.inventory.find( { item : { $type: 10 } } )
于 2012-05-14T21:55:02.540 回答
19

如果您只想计算sent_at值定义为的文档null(不要计算sent_at未设置的文档):

db.emails.count({sent_at: { $type: 10 }})
于 2016-01-17T03:46:43.493 回答
16

利用:

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

它计算所有 sent_at 属性为 null 或未设置的电子邮件。上面的查询与下面的相同。

db.emails.count($or: [
  {sent_at: {$exists: false}},
  {sent_at: null}
])
于 2017-04-06T07:03:23.840 回答
10

似乎你可以只做单行:

{ "sent_at": null }
于 2015-04-07T11:04:03.803 回答
1

以上所有答案都是惊人的和正确的。只想对正在使用的答案添加一项改进$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: nullsent_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

于 2021-09-28T08:27:13.817 回答
0

你也可以试试这个:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
于 2019-08-11T17:31:40.410 回答
0

您可以使用 $in 运算符来检查这两种情况

db.emails.find({"sent_at": {$in:[null,""]}).count()
于 2021-06-10T13:11:42.553 回答
0

如果需要在同一文档中检查属性和值是否存在等于 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

于 2021-11-16T13:37:06.643 回答
-1
db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();
于 2020-09-10T15:49:23.947 回答