首页 文章

mongodb:将前一个管道结果的数组引用到下一个管道中

提问于
浏览
0

我正在使用聚合管道 .

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 回答

  • 0

    你的意思是$group

    db.collection.aggregate([
      { "$match": { ... } },  // your query conditions
      { "$group": { 
        "_id": "$author",
        "score": { "$sum": "$score" },
        "views": { "$sum": "$views" }
      }}
    ])
    

    这将"group by" "author" 字段放在 _id 中并使用"accumulator"返回其他属性,例如$sum

    { "_id" : "dave", "score" : 165, "views" : 621 }
    

    有关更多信息,我建议查看显示许多示例的官方文档的Aggregation部分,以及SQL to Aggregation Mapping Chart,如果您对SQL数据库有一定的了解 .

相关问题