I need to generate stats from users collection in Mongodb.
USER schema:
{
_id: ObjectId,
name: string,
city: string,
gender: enunm["Male", "Female"],
}
STATS schema:
[
{
city: string,
Male: number, (number of males in that $city)
Female: number, (number of females in that $city)
}
]
What aggregation pipeline I should use?
I tried something like this:
db.testCollection.aggregate([
{ $group: { _id: "$status", totalQuantity: { $count: "$stats" } } },
]);
2
Answers
Another way to do this:
You want to be using
$cond
to sum conditionally on gender value while grouping, like so:Mongo Playground