MongoDB:如何查询字段为空或未设置的记录? [英] MongoDB: How to query for records where field is null or not set?

查看:373
本文介绍了MongoDB:如何查询字段为空或未设置的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Email document which has a sent_at date field:

{
  'sent_at': Date( 1336776254000 )
}

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

If this Email has not been sent, the sent_at field is either null, or non-existant.

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

I need to get the count of all sent/unsent Emails. I'm stuck at trying to figure out the right way to query for this information. I think this is the right way to get the sent count:

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

但是我应该如何计算未发送的邮件呢?

But how should I get the count of the ones that aren't sent?

推荐答案

如果send_at字段未设置时不存在,则:

If the sent_at field is not there when its not set then:

db.emails.count({sent_at: {$exists: false}})

如果它在那里并且为null,或者根本不存在:

If its there and null, or not there at all:

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

请参阅此处进行查询并返回null

这篇关于MongoDB:如何查询字段为空或未设置的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆