Skip to content
Advertisement

Add Timestamp while insertMany() in mongoDB

Hi I am MySQL user and new to mongoDB. I get data from my IOT devices as following:

JavaScript

I am inserting it into mongoDB using PHP CodeIgnitor as following:

JavaScript

data is getting inserted in collection named as given key as following:

JavaScript

Now I want to add timestamp to every row getting inserted. I want data getting inserted as following :

JavaScript

is there any way to make mongoDB add current timestamp auto like MySQL?

Advertisement

Answer

First of all you should not store date/time values as string! It will just generate trouble at later times. Better use

JavaScript

"Time": new Date("2020-01-26 00:00:02") may also work

Then in general you don’t need to insert a timestamp. Every document gets an internal _id identifier which contains also the time when it was inserted. You can try like this:

JavaScript

Result:

JavaScript

You can also query for it, e.g.

JavaScript

However, if you like to insert timestamp explicitly then simply do it like this.

JavaScript

Or "timestamp": ISODate() should also work

Another note, this embedded document "_id": {"$id": "5e330be3f7577f640d2a0923"} looks really strange. I assume this is a bug. The string look like a ObjectId object used for _id. Somehow you scratched it.

Update

I really recommend to use proper data types. In PHP the insert could look like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement