How to add a key in a mongo document on the basis of an existing key?

I have a document as follows:

{
    "_id": "1234",
    "created_at": 1678787680
}

I want to modify the document and add a new key updated_at which will be a datetime equivalent of the created_at UNIX timestamp.

{
    "_id": "1234",
    "created_at": 1678787680,
    "updated_at": "2023-03-14 15:39:18.767232"
}

Is there a way to perform this operation using updateMany?

Hey :wave: @Anuj_Panchal1,

Welcome to the MongoDB Community forums :sparkles:

You can use the following aggregation pipeline to do so:

db.test.updateMany(
    {},
    [
        {
            $set: { updated_at: { $toDate: { $multiply: ['$created_at', 1000] } } }
        }
    ]
);

Here I’ve used $toDate to convert a value to a date by multiplying it with 1000 to convert it into milliseconds.

Here UNIX timestamp is the the number of seconds between a particular date and the Unix Epoch on January 1st, 1970 at UTC

So, to convert it to BSON Date we have to multiply by 1000 because in MongoDB - “Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch on January 1st, 1970 at UTC”

After executing, it will return the following output:

{
  "_id": "1234",
  "created_at": 1678787680,
  "updated_at": 2023-03-14T09:54:40.000+00:00
}

I hope it helps!

Best,
Kushagra

2 Likes

You can use update query with $set operator to add new key.
collection.update(
{ ‘_id’ : “1234”},
{ “$set” : { “updated_at”: “2023-03-14 15:39:18.767232”} } )

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.