skip to Main Content

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


  1. You have to have accumulator object upon which mongoDB is grouping the values

    Try this

    People.aggregate([
        {
          $group: {
            _id: "$person.email",
            traveled_to:{
              $push:{
                traveled_to: "$person.traveled_to",
                someinfo: "$person.someinfo"
              }
            },
          },
        },
      ]
    
    Login or Signup to reply.
  2. You must wrap mongoose schema using "{ }" bracket.
    like->

        People.aggregate({
         [
       {
              $group: {
                person: {
                  email: '$email',
                },
              },
            },]
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search