Chicky
Chicky

Reputation: 1257

Mongo. How I can update createdAt by timestamp of _id

My current data does not included createdAt yet. Now I want to write a script to update all exist records.

I tried with:

db.getCollection('storageunits').aggregate([
    {
        "$addFields": {
            "createdAt": "$_id.getTimestamp()"
         }
    }
])

but it didn't work.

Upvotes: 2

Views: 1311

Answers (1)

Valijon
Valijon

Reputation: 13103

Calculate timestamp from _id

Option 1

You can use $toLong with combination of $toDate or $convert operators for _id field (>= v4.0):

db.getCollection('storageunits').aggregate([
  {
    $addFields: {
      "createdAt": {
        $toLong: {
          $toDate: "$_id"
        }
      }
    }
  }
])

MongoPlayground | with $convert

Option 2

You can use $toDate or $convert operators for _id field and subtract 01/01/1970 (>= v4.0):

db.getCollection('storageunits').aggregate([
  {
    $addFields: {
      "createdAt": {
        $subtract: [
          {
            $toDate: "$_id"
          },
          new Date("1970-01-01")
        ]
      }
    }
  }
])

MongoPlayground | Convert date to timestamp

Update collection with createdAt

Option 1

Add extra operator to your aggregation (>= v4.0).
This will override entire collection with documents from aggregation result

{$out: "storageunits"}

Option 2

Since MongoDB v4.2, we can perform aggregation inside update method

db.getCollection('storageunits').update({},
  [
    { "$set": { "createdAt": { $toLong: { $toDate: "$_id" }}}}
  ],
  { "multi" : true}
)

Upvotes: 1

Related Questions