【发布时间】:2018-09-21 01:15:52
【问题描述】:
我正在尝试执行一个棘手的聚合以返回集合中文档内嵌套数组的大小。
这里是如何重新创建我的示例数据:
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]
}
]
}]
提前致谢!
【问题讨论】:
-
在这里对您的问题没有多大帮助,但想说这是一个措辞恰当的问题,适合初学者
标签: javascript node.js mongodb aggregation-framework