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

146
Views
¿Cómo sacar el documento dentro de un campo después de "agrupar por" en MongoDB?

Los documentos en los que trabajo son así:

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

Esta es la consulta que utilicé:

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

La salida final tiene la forma:

 { { "_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" } } };

Pero quiero la salida como:

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

Esto significa que quiero sacar esos documentos dentro del campo myItem . ¿Cómo puedo hacer eso?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Podrías usar $replaceRoot

Jugar

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

Hay errores de sintaxis en su salida.

"id" : 98syf87erfw8n , no es válido.

Debería ser "id" : "98syf87erfw8n" , tenga en cuenta las comillas

Falta una coma después de yearPublished en el segundo objeto.

over 4 years ago · Santiago Trujillo Report

0

Una etapa más del proyecto después de que $group pueda hacer el trabajo:

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

patio de recreo

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!