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

105
Vistas
MongoDB - $addToSet for an Array?

Structure:

[
 {
  "_id": "12",
  "title": "Vanella Icream",
  "contain":"sugar",
  "details": [
      {
        "flavour": "Vanella"
      },
      {
        "weight": "6KG"
      }
   ]
 },
 {
  "_id": "3",
  "title": "Pretzels",
  "contain":"salt",
  "details": [
      {
        "flavour": "Wheat"
      },
      {
        "weight": "2KG"
      }
   ]
 }
]

Expected Output

details:
{
      "flavour": [
        "Vanella",
        "Wheat",
      ],
      "weight": [
        "6KG",
        "2KG",
      ]
}

More Important: I've to do this without details.flavour or details.weight.

I’ve tried with $addToSet, $filter $group but I’m not getting results like that. anyone please suggest.

Mongo Playground: https://mongoplayground.net/p/SXw3jaRDzLy

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  • $project to show required field
  • $unwind deconstruct the details array
  • $objectToArray convert details object to array key-value format
  • $unwind deconstruct the details array
  • $group by details key and construct the array of values
  • $group by null and construct the array of details in key-value format
  • $arrayToObject convert above result from key-value format array of object to an object
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      details: 1
    }
  },
  { $unwind: "$details" },
  {
    $project: {
      details: { $objectToArray: "$details" }
    }
  },
  { $unwind: "$details" },
  {
    $group: {
      _id: "$details.k",
      v: { $addToSet: "$details.v" }
    }
  },
  {
    $group: {
      _id: null,
      details: {
        $push: { k: "$_id", v: "$v" }
      }
    }
  },
  {
    $project: {
      _id: 0,
      details: { $arrayToObject: "$details" }
    }
  }
])

Playground

about 4 years ago · Juan Pablo Isaza 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