我正在尝试执行棘手的聚合,以返回集合中文档中嵌套数组的大小。
这是重新创建示例数据的方法:
db.test.insert({
projects: [
{
_id: 1,
comments: [
'a',
'b',
'c'
]
},
{
_id: 2,
comments: [
'a',
'b'
]
},
{
_id: 3,
comments: []
}
]
})
我将执行的聚合在此处进行:
db.test.aggregate([
// enter aggregation here
])
这是所需的输出:
[{
projects: [
{
_id: 1,
comment_count: 3
},
{
_id: 2,
comment_count: 2
},
{
_id: 3,
comment_count: 0
}
]
}]
我在努力写这个。如果我尝试以下操作:
"projects.comment_count": {"$size": }
结果返回结果数组的大小:
[{
projects: [
{
_id: 1,
comment_count: 3
},
{
_id: 2,
comment_count: 3
},
{
_id: 3,
comment_count: 3
}
]
}]
如果我尝试使用$ map方法,例如:
"projects.comment_count": {
"$map": {
"input": "$projects",
"as": "project",
"in": {
"$size": "$$project.comments"
}
}
}
它将为该数组中的每个对象返回一个看起来像这样的数组:
[{
projects: [
{
_id: 1,
comment_count: [3, 2, 0]
},
{
_id: 2,
comment_count: [3, 2, 0]
},
{
_id: 3,
comment_count: [3, 2, 0]
}
]
}]
提前致谢!
下面是使用一个想法$unwind
,$group
然后$push
用$size
。终于$project
摆脱了_id
:
db.collection.aggregate([
{
"$unwind": "$projects"
},
{
$group: {
_id: null,
"projects": {
$push: {
_id: "$projects._id",
comment_count: {
$size: "$projects.comments"
}
}
}
}
},
{
"$project": {
"_id": 0
}
}
])
你可以在这里看到结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句