Sandeep Sharma
Sandeep Sharma

Reputation: 1885

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?

Upvotes: 2

Views: 1733

Answers (2)

You have to use CURRENT

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

Upvotes: 2

Neil Lunn
Neil Lunn

Reputation: 151132

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 _idand 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.

Upvotes: 0

Related Questions