Simple method to set current timestamp in mongoDB

What is the simple method to set current date and time when new user is inserted to mongoDB??

Currently i used this library to set BSON date format but, once when i update my app dependency that got deprecated. So, can any one help me out?

There is no real easy way to do something like this. If you were to use a SQL database, you would be able to use a trigger. Unfortunately there is nothing analogous to triggers within MongoDB.

Some people have managed to do some hacks / tricks in order to accomplish this. It requires that you setup mongo to use a replica set though as it relies on the oplog. A quick Google search lead me to this StackOverflow question. It does not use Elixir as the answer, but it should give you a general idea of how to do something like this.

If you do not want to attempt to do this kind of stuff yourself, you can take advantage of the mongodb_ecto package. It has not has a release in a little while, but if you use the ecto-2 branch from GitHub, you should be set. I have been using that branch in production for a few months at this point without issues.

if you use an ObjectId as a primary key, you have already the current time encoded into the primary key. depending on your queries, you do not need another dedicated time stamp.

How can i find whether current time is encoded in a primary key object_id? and how to extract time from that object_id??


Thank you :slight_smile:

Only we can get timestamp from object_id. Can’t we set timestamp in another new field when new object is created?? because later i want to update that timestamp.

function BSON.DateTime.from_datetime/1 is undefined (module BSON.DateTime is not available) error when i am trying to convert {{2017, 8, 7}, {7, 56, 42, 875000}} into a BSON.DateTime struct.

BSON.DateTime was removed from mongodb on 0.3.0 version ( ). You have to use native elixir datetime.