Vladimir Vladimir - 18 days ago 9
Node.js Question

Aggregation mongoose $sum where

I have query something like this:

{"$match": {$or: [{"to": system.mongoose.Types.ObjectId(userId)}, {"from": system.mongoose.Types.ObjectId(userId)}]}},
{"$sort": {"createDate": -1}},
{
"$group": {
"_id": "$conversationId",
"from": {"$first": "$from"},
"to": {"$first": "$to"},
"content": {"$first": "$content"},
"createDate": {"$first": "$createDate"},
"unreaded": {"$sum": 1}
}

},


I don't need to edit main
$match
I just need to get sum of
unreaded
messages,

I need something like this:
"unreaded": {"$sum": 1, {$match: {unreaded: true}}}


Any solution for this?

Answer

Use $cond

"unreaded": {"$sum": {$cond: {if: "$unreaded", then: 1, else: 0} }}

Documentation:
https://docs.mongodb.com/manual/reference/operator/aggregation/cond/