Skip to content
Advertisement

Adding a created date field from _id to all mongo documents

I am trying to add a new field createdDate to all existing documents using _id field. I am doing this for easy readability of the documents. I tried following snippet but it is not working.

dbase.collection("cname").updateMany(
  {},
  { $set: { createdDate: new Date(parseInt("$_id".substring(0, 8), 16) * 1000) } } 
)
.then((resp)=>{ console.log('complete') })

This is the createdDate for all my documents now (after running the query): “1970-01-01T00:00:00.000+00:00”

What is wrong with my code ?

Advertisement

Answer

You need to use update with aggregation pipeline starting from MongoDB 4.2,

  • $toDate to cast type to date from _id
dbase.collection("cname").updateMany(
  {},
  [{ 
    $set: { createdDate: { $toDate: "$_id" } } 
  }]
)
.then((resp) => { console.log('complete') });

Playground

Advertisement