Sunday, 7 May 2017

Calculate $sum with default value

I would like to calculate total spending per specific call.

I am collecting orders with specific callId and then sum totalPrice attributes from the result.

It works, except if there is no order, I get an empty array. I would like to get 0 as default value for totalSpending instead.

This is my query:

Order.aggregate({
    $match: { callId: mongoose.Types.ObjectId(callId) }
}, {
    $group: { _id: null, totalSpending: { $sum: '$totalPrice' } }
})

If there is no order I get an empty array, if there is at least 1 order I get [ { _id: null, totalSpending: 50 } ] for example.



via user2604170

No comments:

Post a Comment