Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda