Reputation: 1759
I have a MongoDB collection which looks like this:
{user: "1", likes: 111, isEnabled: true},
{user: "1", likes: 222, isEnabled: false},
{user: "2", likes: 333, isEnabled: false},
{user: "2", likes: 444, isEnabled: false},
I want to sum group the them up by the user, sum up the likes and check if one of the documents of a user has "isEnabled" = true (basically a logical OR).
I want this result at the end:
{user: "1", allLikes: "333", isAnyEnabled: true},
{user: "2", allLikes: "777", isAnyEnabled: false},
I can use the $sum
accumulator of the group
stage to sum up the likes. My problem is that there seems to be no group
operator which supports logical operations on booleans. Is there any way to do this?
I tried this so far
db.myCollection.aggregate([{$match: {
"_id":"$user",
"allLikes": {
"$sum": "$likes"
},
"isAnyEnabled":{"$or":"$isEnabled"}
}}])
But it seems that $or
is not supported for this: unknown group operator '$or'
Upvotes: 1
Views: 253
Reputation: 15187
You can use $anyElementTrue
in a project stage like this:
$group
by _id
to get all likes sumed and a list of all isEnabled
values$anyElementTrue
to check if there is at least one true
and then isAnyEnabled
is true or false.db.collection.aggregate([
{
"$group": {
"_id": "$user",
"allLikes": {
"$sum": "$likes"
},
"enabled": {
"$push": "$isEnabled"
}
}
},
{
"$project": {
"_id": "$_id",
"allLikes": "$allLikes",
"isAnyEnabled": {
"$anyElementTrue": [
"$enabled"
]
}
}
}
])
Example here
Upvotes: 2