Use updateMany to create a new date field based on a millis field

Hi @Allan_Chase,

Have you tried using $toDate to see if that works for you? If the below doesn’t work for you, please provide some sample documents, advise the expected output and MongoDB version you are using.

The below was run on a 7.0.2 test environment and using updateOne().

Inserting the test document:

test> db.collection.find()

test> db.collection.insertOne({'createdAtMillis': 1693958185963})
{
  acknowledged: true,
  insertedId: ObjectId('65643590c23a657c48db154f')
}
test> db.collection.find()
[
  {
    _id: ObjectId('65643590c23a657c48db154f'),
    createdAtMillis: 1693958185963
  }
]

Updating the document and setting the createdUTCDate field:

test> db.collection.updateOne({},[{'$set':{'createdUTCDate':{'$toDate':'$createdAtMillis'}}}])
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
test> db.collection.find()
[
  {
    _id: ObjectId('65643590c23a657c48db154f'),
    createdAtMillis: 1693958185963,
    createdUTCDate: ISODate('2023-09-05T23:56:25.963Z')
  }
]
test> 

FWIW here is the specific update pipeline used:

[{'$set':{'createdUTCDate':{'$toDate':'$createdAtMillis'}}}]

You may wish to test the updateMany() variant on a test environment first to see if there are any caveats before as well as making a backup of the data before trying this on production.

Regards,
Jason