Auto populate date in MongoDB on insert

后端 未结 4 1256
说谎
说谎 2021-01-05 03:54

MongoDB provides a way to update a date field by the system on update operations: https://docs.mongodb.com/manual/reference/operator/update/currentDate/. Is there any equiva

4条回答
  •  星月不相逢
    2021-01-05 04:16

    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.

提交回复
热议问题