我有这样的收藏:
{
"_id" : ObjectId("4d663451d1e7242c4b68e000"),
"topic" : "abc",
"subLevel" : {
"id" : 1
}
}
{
"_id" : ObjectId("4d6634514cb5cb2c4b69e000"),
"topic" : "bce",
"subLevel" : {
"id" : 1
}
}
{
"_id" : ObjectId("4d6634514cb5cb2c4b70e000"),
"topic" : "bec",
"subLevel" : {
"id" : 2
}
}
{
"_id" : ObjectId("4d6634514cb5cb2c4b70e000"),
"topic" : "vvv",
"subLevel" : {
"id" : 3
}
}
并且我需要计算提供的subLevel.id列表中存在多少个文档,例如,如果我提供1和2,它应该告诉我,对于1我们有2个文档,对于2我们只有1个文档,只是忽略了subLevel.id为3,因为它不在ID列表中。
我试图做到这一点
db.getCollection('products').aggregate( [
{ $project:
{ "has_sublevel" : {$in: [ "subLevel.id", [1 , 2 ]]} }
},
{ $group: { _id : "$subLevel.id", count: { $sum: 1 } } }
] )
但是结果是
{
_id : null,
count: 4
}
我该怎么办,谢谢!
如果将其转换为我更熟悉的SQL,查询应如下所示:
select subLevelId, count(id) FROM products where subLevelId in (1,2) group by subLevelId
如果我理解正确,那么您是如此亲密,请检查以下查询:
$match
时仅获取subLevel.id
1或2的文档。$group
通过id
和求和得到总数:db.collection.aggregate([
{
"$match": { "subLevel.id": { "$in": [ 1, 2 ] } }
},
{
"$group": { "_id": "$subLevel.id", "count": { "$sum": 1 } }
}
])
这里的例子
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句