Home > Blockchain >  How to add timestamp of inserting a document from external source in mongodb
How to add timestamp of inserting a document from external source in mongodb

Time:12-28

I am new to mongo db, I am trying to insert a vector of documents into MongoDb from an external source(cloud database). I want to add the timestamp of when the document is loaded in mongodb along with the document I am inserting. I don't want to update the document later with adding a time field. How do I do this? For example: Below is the json format of the document I am getting from cloud

{_id:123
cloudtimestamp:"20201212T5:00:00.000 00.00"
data:{
val1:2
val2:3
}
//TO-DO add insertTimestamp

}

Before I insert the above document into mongodb, I want to add the insertion timestamp in the place of //TO-DO comment

CodePudding user response:

One way to solve OP's situation is to keep the default behaviour of populating with an ObjectId and only maintain a modified_at timestamp.

According to the official MongoDB documentation of ObjectId,

The 12-byte ObjectId value consists of:

a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch

Thus the insertion/creation time can be fetched by using $toDate.

  • Related