简体   繁体   中英

mongodb: Reference previous pipeline result's array into next pipeline

I'm using the aggregate pipeline.

 const pipeline = [
                    { $match: query } // first pipeline stage
 ]

this would give following result:

{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 }

{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }

I want to reduce this pipeline result(which is an array in this case) into an object. I know, we can reduce with project

Second pipeline stage:

{
  $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?

You have to use CURRENT

{
  $project: {
   results: {
    $reduce: {
        input: $$CURRENT, 
        initialValue: <expression>,
        in: <expression>
    }
   }
}

You mean $group

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

This would "group by" the "author" field which is placed in the _id and return the other properties using an "accumulator" such as $sum

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

For more information I suggest looking at the Aggregation section of the official documentation which shows many samples, as well as the SQL to Aggregation Mapping Chart if you have some familiarity with SQL Databases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM