How to group by two fields whose value my be same and count them

84 views Asked by At

i have a collection named players, below is the sample document. now i want to fetch the user-wise count of players for which the user is either mentor or owner or both. help me with a mongodb aggregation pipeline. (here user means owner or mentor)

    {
        "_id": ObjectId("32521df3f4948bd2f54223"),
        "firstName": "Olivia",
        "lastName": "Moore",
        "email": "[email protected]",
        "owner_id": ObjectId("32521df3f4948bd2f54988"),
        "mentor_id": ObjectId("32521df3f4948bd2f12343")
    },

`

i tried below aggregation. but user wise count not accurate.

db.players.aggregate([
    {
        $group: {
            _id: { $ifNull: ["$owner_id", "$mentor_id"] },
            playerCount: { $sum: 1 }
        }
    },
    {
        $project: {
            user_id: "$_id",
            playerCount: 1,
            _id: 0
        }
    }
]);

1

There are 1 answers

3
rickhg12hs On BEST ANSWER

If I understand correctly, here's one way you may be able to "fetch the user-wise count of players for which the user is either mentor or owner or both."

db.players.aggregate([
  {
    "$project": {
      "_id": 0,
      "ownersMentors": {
        "$setUnion": [["$owner_id"], ["$mentor_id"]]
      }
    }
  },
  {"$unwind": "$ownersMentors"},
  {
    "$group": {
      "_id": "$ownersMentors",
      "playerCount": {"$sum": 1}
    }
  },
  {
    "$project": {
      "_id": 0,
      "user_id": "$_id",
      "playerCount": 1
    }
  }
])

Try it on mongoplayground.net.