我将尝试执行一个棘手的聚合操作,以返回集合中文档内嵌数组的大小。
以下是重新创建样本数据的方法:
我将执行的聚合操作在此处:
以下是期望的输出:
对于数组中的每个对象,它将返回一个类似于这样的数组:
感谢您的提前支持!
以下是重新创建样本数据的方法:
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]
}
]
}]
感谢您的提前支持!