YulePale
YulePale

Reputation: 7706

MongoDB aggregation: conditional aggregation stages

Is it possible to have conditional aggregation stages depending on returned variables from aggregation?

For example

User.aggregate([
    // if user has a property verified that returns true run aggregation pipeline
    // one. Else run aggregation pipeline 2.
])

Upvotes: 1

Views: 4862

Answers (1)

matthPen
matthPen

Reputation: 4353

Of course you can, by using $facet with 2 different pipelines, and put for each first stage a $match stage with your property verification.

Here's an example of such a query:

db.collection.aggregate([
  {
    "$facet": {
      "avgSteps": [
        {
          "$match": {
            hasCar: false
          }
        },
        {
          $project: {
            steps: {
              $avg: "$walks.steps"
            }
          }
        }
      ],
      "sumDistance": [
        {
          "$match": {
            hasCar: true
          }
        },
        {
          $project: {
            sumKm: {
              $sum: "$travels.distance"
            }
          }
        }
      ],
      
    }
  }
])

You can test it here.

Upvotes: 8

Related Questions