我正在使用聚合管道 .
const pipeline = [
{ $match: query } // first pipeline stage
]
这将得到以下结果:
{“_ id”:ObjectId(“512bc95fe835e68f199c8686”),“author”:“dave”,“score”:80,“views”:100} {“_ id”:ObjectId(“512bc962e835e68f199c8687”),“author”:“戴夫“,”得分“:85,”观看次数“:521}
我想将此管道结果(在这种情况下是一个数组)减少到一个对象中 . 我知道,我们可以减少项目
第二个管道阶段:
{
$project: {
results: {
$reduce: {
input: <array>, // We have $$ROOT, but I need previous pipeline result
initialValue: <expression>,
in: <expression>
}
}
}
How could we reference previous pipeline result as an array into this pipeline stage?
1 回答
你的意思是$group
这将"group by"
"author"
字段放在_id
中并使用"accumulator"返回其他属性,例如$sum有关更多信息,我建议查看显示许多示例的官方文档的Aggregation部分,以及SQL to Aggregation Mapping Chart,如果您对SQL数据库有一定的了解 .