Reputation: 7706
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
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"
}
}
}
],
}
}
])
Upvotes: 8