具有猫鼬聚合和求和嵌套字段的节点
Node with mongoose aggregate and sum nested fields
当我对 collection...
执行此查询时
models.Project.find(function(err, result) {
//result = doc below
}).populate('media')
...我得到这个结果:
{
_id: 57f36baa6cf34d079c8474a0,
code: 'ZMIA',
__v: 0,
media:[
{
_id: 57f36bb26cf34d079c847766,
project_code: 'ZMIA',
amount: 228,
__v: 0
},
{
_id: 57f36bb26cf34d079c84775c,
project_code: 'ZMIA',
amount: 250,
__v: 0
}
]
},
{
_id: 57f36baa6cf34d079c8474a1,
code: 'ZMJU',
__v: 0,
media: []
}
media
是一个参考字段。如何将嵌套媒体 objects(如果存在)聚合到 $sum
amount
字段并将结果按 project_code
分组?
您可以使用聚合框架,其中 运行 聚合管道由扁平文档上的初始 $unwind
pipeline that will denormalize the media
field since it is an array and then a $lookup
operator to do a left join to the collection that has the media
refs. A further $unwind
operator is needed to flatten the array field produced as a result of the join and then do a $group
运算符管道组成,以生成期望的结果。
运行 以下管道应该适合您:
models.Project.aggregate([
{ "$unwind": "$media" },
{
"$lookup": {
"from": "media", // <-- collection to join
"localField": "media",
"foreignField": "_id",
"as": "media_joined"
}
},
{ "$unwind": "$media_joined" },
{
"$group": {
"_id": "$media_joined.project_code",
"total": { "$sum": "$media_joined.amount" }
}
}
], function(err, result){
console.log(result);
})
当我对 collection...
执行此查询时models.Project.find(function(err, result) {
//result = doc below
}).populate('media')
...我得到这个结果:
{
_id: 57f36baa6cf34d079c8474a0,
code: 'ZMIA',
__v: 0,
media:[
{
_id: 57f36bb26cf34d079c847766,
project_code: 'ZMIA',
amount: 228,
__v: 0
},
{
_id: 57f36bb26cf34d079c84775c,
project_code: 'ZMIA',
amount: 250,
__v: 0
}
]
},
{
_id: 57f36baa6cf34d079c8474a1,
code: 'ZMJU',
__v: 0,
media: []
}
media
是一个参考字段。如何将嵌套媒体 objects(如果存在)聚合到 $sum
amount
字段并将结果按 project_code
分组?
您可以使用聚合框架,其中 运行 聚合管道由扁平文档上的初始 $unwind
pipeline that will denormalize the media
field since it is an array and then a $lookup
operator to do a left join to the collection that has the media
refs. A further $unwind
operator is needed to flatten the array field produced as a result of the join and then do a $group
运算符管道组成,以生成期望的结果。
运行 以下管道应该适合您:
models.Project.aggregate([
{ "$unwind": "$media" },
{
"$lookup": {
"from": "media", // <-- collection to join
"localField": "media",
"foreignField": "_id",
"as": "media_joined"
}
},
{ "$unwind": "$media_joined" },
{
"$group": {
"_id": "$media_joined.project_code",
"total": { "$sum": "$media_joined.amount" }
}
}
], function(err, result){
console.log(result);
})