Assume I have database structure as;
[
{name: "alex" , surname: "brown" , school: "washington"},
{name: "felix" , surname: "yellow" , school: "georgia"},
{name: "felix" , surname: "yellow" , school: "georgia"},
{name: "tommy" , surname: "brown" , school: "davis"},
{name: "tommy" , surname: "brown" , school: "davis"},
{name: "tommy" , surname: "brown" , school: "davis"},
{name: "tommy" , surname: "brown" , school: "davis"}
]
What I want to do is group them by their school info. So expected result is;
{
school: davis
students: [
{name: "tommy" , surname: "brown"},
{name: "tommy" , surname: "brown"},
{name: "tommy" , surname: "brown"},
{name: "tommy" , surname: "brown"},
]
},
{
school: georgia
students: [
{name: "felix" , surname: "yellow"}
]
},
{
school: washington
students: [
{name: "alex" , surname: "brown"}
]
}
To be able to this I think about using $group as;
db.collection.aggregate([
{$group: {"_id" : "$school", name : "$name" , surname: "$surname"}}
])
But I think, I misunderstood the $group. So how can I wrote this query?
via mmu36478
No comments:
Post a Comment