[英]MongoDB Aggregation $size on Nested Field
I'm trying to perform a tricky aggregation to return the size of a nested array within a document in the collection. 我正在尝试执行一个棘手的聚合,以返回集合中文档中嵌套数组的大小。
Here is how to re-create my sample data: 以下是重新创建示例数据的方法:
db.test.insert({
projects: [
{
_id: 1,
comments: [
'a',
'b',
'c'
]
},
{
_id: 2,
comments: [
'a',
'b'
]
},
{
_id: 3,
comments: []
}
]
})
The aggregation I would perform goes here: 我将执行的聚合在这里:
db.test.aggregate([
// enter aggregation here
])
Here is the desired output: 这是所需的输出:
[{
projects: [
{
_id: 1,
comment_count: 3
},
{
_id: 2,
comment_count: 2
},
{
_id: 3,
comment_count: 0
}
]
}]
I'm struggling with how to write this. 我正在努力解决这个问题。 If I try the following:
如果我尝试以下方法:
"projects.comment_count": {"$size": }
The result returns the size of the resulting array: 结果返回结果数组的大小:
[{
projects: [
{
_id: 1,
comment_count: 3
},
{
_id: 2,
comment_count: 3
},
{
_id: 3,
comment_count: 3
}
]
}]
If I try to use the $map method like this: 如果我尝试使用这样的$ map方法:
"projects.comment_count": {
"$map": {
"input": "$projects",
"as": "project",
"in": {
"$size": "$$project.comments"
}
}
}
It will return an array that looks like this for each object in the array: 它将为数组中的每个对象返回一个如下所示的数组:
[{
projects: [
{
_id: 1,
comment_count: [3, 2, 0]
},
{
_id: 2,
comment_count: [3, 2, 0]
},
{
_id: 3,
comment_count: [3, 2, 0]
}
]
}]
Thanks in advance! 提前致谢!
Here is an idea using $unwind
, $group
and then $push
with $size
. 这是一个使用
$unwind
, $group
然后$push
with $size
的想法。 Finally $project
to get rid of that _id
: 最后
$project
摆脱那个_id
:
db.collection.aggregate([
{
"$unwind": "$projects"
},
{
$group: {
_id: null,
"projects": {
$push: {
_id: "$projects._id",
comment_count: {
$size: "$projects.comments"
}
}
}
}
},
{
"$project": {
"_id": 0
}
}
])
You can see the result here 你可以在这里看到结果
You need to specify each field inside the in
argument of $map
aggregation and finally use $size
with the comments
array. 您需要
in
$map
aggregation的in
参数内指定每个字段,最后使用带comments
数组的$size
。
Something like this 像这样的东西
db.collection.aggregate([
{ "$project": {
"projects": {
"$map": {
"input": "$projects",
"in": {
"_id": "$$this._id",
"comment_count": {
"$size": "$$this.comments"
}
}
}
}
}}
])
Output 产量
[
{
"projects": [
{
"_id": 1,
"comment_count": 3
},
{
"_id": 2,
"comment_count": 2
},
{
"_id": 3,
"comment_count": 0
}
]
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.