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

232
Vistas
MongoDB: $mergeObjects is overwriting object data in update pipeline

When using $mergeObjects in update pipeline, the original object is being overwritten. Are there any alternatives to avoid this from happening or can $mergeObjects be used in any way to avoid this.

I have a document as follows:

{
    "employment": {
      "selfEmployed": {
          "netProfit": 1000,
          "addbacks": [
              {
                "addbackId": "5a934e000102030405000001",
                "value": 1000,
              }
            ]
      }
    }
}

I have update data as follows:

const update = {
    "selfEmployed": {
        "netProfit": 22,
    }
  };

The update query is:

db.collection.update({},
[
  {
    $set: {
      "employment": {
        $mergeObjects: [
          "$employment",
          update
        ]
      }
    }
  }
])

However $mergeObjects overwrites the object to give following result:

  {
    "employment": {
      "selfEmployed": {
        "netProfit": 22
      }
    }
  }

Expected Result:

{
    "employment": {
      "selfEmployed": {
          "netProfit": 22,
          "addbacks": [
              {
                "addbackId": "5a934e000102030405000001",
                "value": 1000,
              }
            ]
      }
    }
}

Playground

Edit 1:

I can only rely on top level field to perform update. Some answers below do work for selfEmployed. But I have other fields on the collection as well. e.g.

{
    "employment": {
      "selfEmployed": {
          "netProfit": 1000,
          "addbacks": [
              {
                "addbackId": "5a934e000102030405000001",
                "value": 1000,
              }
            ]
      },
      "unemployed": {
          "reason": "some reason",
          //... other data
      }
      // .. other data
    }
}

And i don't want to repeat or write multiple queries for updating nested fields and using direct set is out of the question as well. I'm looking for a way using the update pipeline as I have given above.

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

0

According to $mergeObjects Behaviour,

$mergeObjects overwrites the field values as it merges the documents. If documents to merge include the same field name, the field, in the resulting document, has the value from the last document merged for the field.

Hence, the original employment.selfEmployed will be replaced with the new value.


Solution 1: Direct $set value for employment.selfEmployed.netProfit.

db.collection.update({},
[
  {
    $set: {
      "employment.selfEmployed.netProfit": 22
    }
  }
])

Sample Mongo Playground for Solution 1


Solution 2: $mergeObjects for employment.selfEmployed only.

db.collection.update({},
[
  {
    $set: {
      "employment.selfEmployed": {
        $mergeObjects: [
          "$employment.selfEmployed",
          {
            "netProfit": 22
          }
        ]
      }
    }
  }
])

Sample Mongo Playground for Solution 2

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