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

283
Vistas
MongoDB- How to $project items from an object?

Playground https://mongoplayground.net/p/tIMLOtWTnno

DATA:

[

  {
    "_id": "1",
    "data": {                     // How to remove this "data" Field
      "colour": "Blue",
      "size": "12",
    }
  },
  {
    "_id": "2",
    "data": {                     // How to remove this "data" Field
      "colour": "Silver",
      "size": "20",
    }
  }

]

I want to remove the data field.

Expected Output:

[
  {
    "_id": "1",
    "colour": "Blue",
    "size": "12",
    
  },
  {
    "_id": "2",
    "colour": "Silver",
    "size": "20",
    
  }
]

Tried it like this:

db.collection.aggregate({
  $project: {
    _id: 1,
    data: {
      $objectToArray: "$data"
    }
  },
  
},
{
  $unwind: "$data"
},
{
  $project: {
    "$data.k": "$data.v"
  }
})

How to do this ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Query1

  • set to add the fields in the root and remove the data

*you could use also project

Test code here

aggregate(
[{"$set":
  {"colour":"$data.colour",
   "size":"$data.size",
   "data":"$$REMOVE"}}])

Query2

  • more general solution without the need to type each field in project
  • merge the data embeded object with the root, and make it new root
  • remove the data field

Test code here

aggregate(
[{"$replaceRoot":{"newRoot":{"$mergeObjects":["$data", "$$ROOT"]}}},
 {"$project":{"data":0}}])
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