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
}
}
]);
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."
Try it on mongoplayground.net.