Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Mongoose group nested object

Say I have a collection of people with a person object and its associated data.

{  
   _id: '1'
   person:{
    email:"bob@gmail.com"
    traveled_to: 'North Korea',
    someinfo:"random"
    
   }

}

{  
   _id: '2'
   person:{
    email:"bob@gmail.com"
    traveled_to: 'United States'
    someinfo:"very random"
   }
},

{  
   _id: '3'
   person:{
    email:"jack@gmail.com"
    traveled_to: 'Russia'
    someinfo:"super super random"
   }
}


I would like for example to group bob@gmail.com and store his info in an array

{
 _id: '1'
 person:{
  email:"bob@gmail.com"
  travels: [
    {
      traveled_to: 'North Korea',
      someinfo:"random"
    },
    {
      traveled_to: 'United States'
      someinfo:"very random"
    }
  ]

},
{
   _id: '2'
   email:"jack@gmail.com"
   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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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"
          }
        },
      },
    },
  ]
about 4 years ago · Juan Pablo Isaza Report

0

You must wrap mongoose schema using "{ }" bracket. like->

    People.aggregate({
     [
   {
          $group: {
            person: {
              email: '$email',
            },
          },
        },]
      }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!