I have users
collection in my MongoDB with the following schema:
const User = mongoose.Schema({
gender: {
type: String
},
name: {
type: String
},
location: {
type: String
},
email: {
type: String
},
});
Now I need to get the users from the database but in a different schema (or format), the response should like this:
{
"countries":
[
{
"name": <country>,
users: [
{
"name": <name>,
"gender": <gender>,
"email": <email>
}
]
}
]
}
I thought of using User.find()
then transform manually the object but It's a long process and i think it might make me query the database multiple times, so I would like to know if there is a way to get the data the way I want with Mongoose directly. If not what do you suggest?
Thanks!
CodePudding user response:
You have to use Mongodb Aggragation Framework . Group by country , then push users to array .
db.collection.aggregate([
{
"$group": {
"_id": "$location",
"users": {
"$push": {
"name": "$name",
"email": "$email",
"gender": "$gender"
}
}
}
},
{
"$project": {
"_id": 0,
"name": "$_id",
"users": 1
}
},
{
"$sort": {
"name": 1
}
}
])
Here is working example : https://mongoplayground.net/p/RI5h5JYOZf8