Auto populate date in MongoDB on insert

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.

Tags:

Mongodb