Auto Populate Date In MongoDB On Insert


Answer :

You may try to do a few things if you do not want to handle this from code (I have executed the code below directly on mongo shell):

  1. If you want to use $currentDate use update with upsert = true:

    db.orders.update(    {"_id":ObjectId()},    {        $currentDate: {          createtime: true        }    },    { upsert: true } ) 

It will now generate the objectid on app server instead of date/time (unless you use raw command).

  1. Use new timestamp or date object directly:

    db.orders.insert(     "createtime": new Timestamp() ) 

The problem with most driver will be then to make sure the new object is created on mondodb server- not on the machine where the code is running. You driver hopefully allows to run raw insert command.

Both will serve the purpose of avoiding time differences/ time sync issue between application server machines.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?