首页 > 解决方案 > 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

标签: mongodbmongodb-query

解决方案


只需使用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})
})

推荐阅读