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

139
Views
How to get the document inside a field out after "group by" in MongoDB?

The documents I work on are like this:

{
    "id" : "98syf87erfw8n"
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979",
    .
    .
    .
}

This is the query I used:

db.foobar.aggregate([
    { $group : {
        _id : '$yearpublished',
        myItem: { $first: "$$ROOT" }
    }}
])

The final output is in the form:

{
    { "_id" : "1923", "myItem" : {
                            "id" : "98syf87erfw8n",
                            "foo" : { "objectid" : "39", "stuff" : "65" },
                            "yearpublished" : "1979"
                        }
    }, 
    { "_id" : "1453", "myItem" : {
                            "id" : "88888888888",
                            "foo" : { "objectid" : "394", "stuff" : "55" },
                            "yearpublished" : "1453"
                            "author" : "Ravi Kiran"
                        }
    }
};

But I want the output as:

{
    "id" : "98syf87erfw8n",
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979"
},
{
    "id" : "88888888888",
    "foo" : { "objectid" : "394", "stuff" : "55" },
    "yearpublished" : "1453",
    "author" : "Ravi Kiran"
}

This means I want to get those documents inside the field myItem out. How can I do that?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could use $replaceRoot

Play

db.collection.aggregate({
  "$replaceRoot": {
    "newRoot": "$myItem"
  }
})

There are syntax errors in your output.

"id" : 98syf87erfw8n, is invalid.

It should be "id" : "98syf87erfw8n", Note the quotes

There is comma missing after yearPublished in the second object.

over 4 years ago · Santiago Trujillo Report

0

One more project stage after the $group can do the job:

{
 $project: {
  yearpublished: "$myItem.yearpublished",
  foo: "$myItem.foo",
  id: "$myItem.id",
  _id: 0
 }
}

playground

over 4 years ago · Santiago Trujillo 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!