Peter
Peter

Reputation: 1759

MongoDB Use logical OR in group stage

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

Answers (1)

J.F.
J.F.

Reputation: 15187

You can use $anyElementTrue in a project stage like this:

  • First $group by _id to get all likes sumed and a list of all isEnabled values
  • Then use $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

Related Questions