Insert data from one existing field to another so that they contain the same information

Hello good morning.

Could you please help me,

I want to insert the data from one field to another field within the same collection in a massive way that applies to all documents in the collection.

example:

“trail”: {
“idUsuarioCreacion”: “499”,
“idUsuarioActualizacion”: “”,
“fechaHoraCreacion”: “2023-03-13T18:17:59.532Z”
“fechaHoraActualizacion”: “”,
}

the information from the “idUsuarioCreacion” field must be replicated in the “idUsuarioActualizacion” field
as well as the information of “fechaHoraCreacion” in “fechaHoraActualizacion”.

First of all, Thanks.

Hi Edith,

Not sure if this suits your use case, but I believe the following may work:

Test data:

DB>db.collection.find({},{_id:0})
[
  {
    trail: {
      idUsuarioCreacion: '599',
      idUsuarioActualizacion: '',
      fechaHoraCreacion: '2022-01-11T18:17:59.532Z',
      fechaHoraActualizacion: ''
    }
  },
  {
    trail: {
      idUsuarioCreacion: '499',
      idUsuarioActualizacion: '',
      fechaHoraCreacion: '2023-03-13T18:17:59.532Z',
      fechaHoraActualizacion: ''
    }
  }
]

the updateMany() used with a pipeline containing $set:

DB>db.collection.updateMany({},
[
  {
    '$set': {
      'trail.idUsuarioActualizacion': '$trail.idUsuarioCreacion',
      'trail.fechaHoraActualizacion': '$trail.fechaHoraCreacion'
    }
  }
])

Documents mentioned above after the update:

DB>db.collection.find()
[
  {
    _id: ObjectId("64251cbb6e5491f12577f41f"),
    trail: {
      idUsuarioCreacion: '599',
      idUsuarioActualizacion: '599',
      fechaHoraCreacion: '2022-01-11T18:17:59.532Z',
      fechaHoraActualizacion: '2022-01-11T18:17:59.532Z'
    }
  },
  {
    _id: ObjectId("64251cbe6e5491f12577f420"),
    trail: {
      idUsuarioCreacion: '499',
      idUsuarioActualizacion: '499',
      fechaHoraCreacion: '2023-03-13T18:17:59.532Z',
      fechaHoraActualizacion: '2023-03-13T18:17:59.532Z'
    }
  }
]

If you believe this may work for your use case, I would test and verify it meets your requirements in a test environment thoroughly beforehand as you mentioned you need to update the whole collection. In my example, I have only done this on 2 sample documents.

Regards,
Jason

1 Like

Thank you very much, it was very helpful.

1 Like

Awesome. Glad to hear it helped!