Vijay Innamuri
Vijay Innamuri

Reputation: 4372

How to get insert time or last updated time as field in MongoDB collection?

In a MongoDB table multiple records will be inserted at a time.

For example below records will the same timestamp

{ "_id" : ObjectId("567a68517507b377a0a20902"), value: "bar", time: "2012" }
{ "_id" : ObjectId("567a68517507b377a0a20903"), value: "baz", time: "2011" }

It's possible to get the timestamp of individual document.

ObjectId("567a68517507b377a0a20903").getTimestamp()
ISODate("2015-12-23T09:24:33Z")

Is it possible to have a field where it automatically generates the last updated or created timestamp to each and every document upon insert?

Similar to CURRENT_TIMESTAMP in MYSQL

Note: Data will be inserted from Apache Spark Streaming

Upvotes: 3

Views: 5414

Answers (2)

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

You can do it using $currentDate. But it works only in update query.

Upvotes: 1

Constantin Guay
Constantin Guay

Reputation: 1664

Depending on your language, yes. In MongoShell, you can use new ISODate()

Upvotes: 0

Related Questions