Search code examples
mongodbmongodb-querymongodb-update

MongoDB - Update data type for the nested documents


I have this collection: (see the full collection here https://mongoplayground.net/p/_gH4Xq1Sk4g)

{
  "_id": "P-00",
  "nombre": "Woody",
  "costo": [
    {
      "tipo": "Cap",
      "detalle": "RAC",
      "monto_un": "7900 ",
      "unidades": "1",
      "total": "7900 "
    }
  ]
}

I tried a lot of ways to transform monto_un, unidades and total into int, but I always get an error. Neither of these works.

db.proyectos.updateMany({}, {'$set': {"costo.monto_un": {'$toInt': 'costo.$.monto_un'}}})
db.collection.update({},
[
  {
    $set: {
      costo: {
        monto_un: {
          $toInt: {
            costo: "$monto_un"
          }
        }
      }
    }
  }
],
{
  multi: true
})

MongoDB 5.0.9
Any suggestions?


Solution

    1. $set - Update costo array.

      1.1. $map - Iterate each element in the costo array and return a new array.

      1.2. $mergeObjects - Merge current document with the document from 1.3.

      1.3. A document with the monto_un field. You need to trim space for the monto_un field in the current iterate document via $trim and next convert it to an integer via $toInt.

    In case you are also required to convert the unidades and total as int, add those fields with the same operator/function logic as monto_un in 1.3. Those fields in the document (1.3) will override the existing value due to $mergeObjects behavior.

    db.collection.update({},
    [
      {
        $set: {
          costo: {
            $map: {
              input: "$costo",
              in: {
                $mergeObjects: [
                  "$$this",
                  {
                    monto_un: {
                      $toInt: {
                        $trim: {
                          input: "$$this.monto_un"
                        }
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    ],
    {
      multi: true
    })
    

    Sample Mongo Playground