Say I have a collection of people with a person object and its associated data.
{
_id: '1'
person:{
email:"[email protected]"
traveled_to: 'North Korea',
someinfo:"random"
}
}
{
_id: '2'
person:{
email:"[email protected]"
traveled_to: 'United States'
someinfo:"very random"
}
},
{
_id: '3'
person:{
email:"[email protected]"
traveled_to: 'Russia'
someinfo:"super super random"
}
}
I would like for example to group [email protected] and store his info in an array
{
_id: '1'
person:{
email:"[email protected]"
travels: [
{
traveled_to: 'North Korea',
someinfo:"random"
},
{
traveled_to: 'United States'
someinfo:"very random"
}
]
},
{
_id: '2'
email:"[email protected]"
travels:[
{
traveled_to: 'Russia'
some_info:'super super random'
}
]
}
I tried something like this
People.aggregate([
{
$group: {
person: {
email: '$email',
},
},
},
]
Although I’m getting a
MongoError: The field ‘person’ must be an accumulator object
Thanks!
2
Answers
You have to have accumulator object upon which mongoDB is grouping the values
Try this
You must wrap mongoose schema using "{ }" bracket.
like->