I have 2 collections
User:
email: { type: String, required: true, unique: true },
team: { type: ObjectId, ref: 'team', required: true},
And Team:
name: { type: String, required: true },
active: { type: Boolean, required: true, default: true},
I want to get all the teams and the number of users in that team, How would I approch this using Mongoose ?
CodePudding user response:
Use the Teams
model and perform an aggregate query.
First we join all users from the users
collection. Then we create an extra field called user_amount
in which we store the size of the users
array. In the last step we remove the users
property but if you need this array just remove the last step of this pipeline.
Teams.aggregate([
{
"$lookup": {
"from": "users",
"localField": "_id",
"foreignField": "team",
"as": "users"
}
},
{
"$addFields": {
"user_amount": {
"$size": "$users"
}
}
},
{
"$unset": "users"
}
])