mongodb - MongoDB:管道阶段之间的空签入
问题描述
如果我像这样创建一个集合:
db.People.insert({"Name": "John"})
并运行一个简单的 mongo 聚合,如下所示:
db.People.aggregate([{$match: {Name: "John"}}, {$group: {_id: "null", count: {$sum: 1}}}])
这会计算集合中的所有 Johns 并返回这个
{ "_id" : "null", "count" : 1 }
这很好。但是,如果我搜索根本不存在的名称“Clarice”,它会返回null
.
我希望它返回
{ "_id" : "null", "count" : 0 }
我还没有找到实现这一目标的方法。$match
我必须在- 和 -阶段之间包含某种空值检查$group
。
解决方案
只需使用count
db. People.count({Name:"John"})
这将返回确切的数字。
否则,您需要检查结果是否为空数组。下面是使用环回的节点代码,
db.People.aggregate([
{$match: {Name: "John"}},
{$group: {_id: "null", count: {$sum: 1}}}
],(err,res)=>{
if(err) return cb(err)
if(res.length) return cb(err,res)
else return cb(err,{_id:null,count:0})
})
推荐阅读
- javascript - 如何使用设置间隔的承诺
- java - 从 BufferedReader 输入整数时如何在 java 中修复 NullPointerException
- php - 遇到错误无法使用 PHP mail() 发送电子邮件。您的服务器可能未配置为使用此方法发送邮件
- asciidoctor - Asciidoctorj:如何允许扩展写入附加文件
- reactjs - 如何使用 ReactJs 和 axios 更新图像
- python - 如何在 django 中获取相互关联的记录?
- python - 在 Python 中查找列表的第二个元素的地址
- laravel-8 - 如何在 Laravel 查询生成器中执行 TRIM()?
- android - 使用 kotlin 协程 Android 在 Activity OnCreate() 中从 DB 加载图像
- javascript - 产品未添加到数据库中