Automatically populate date in MongoDB on insert

MongoDB provides a way to update the date field with the system when performing update operations: https://docs.mongodb.com/manual/reference/operator/update/currentDate/ . Is there an equivalent of this for insert operations?

+4
source share
2 answers

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

  • If you want to use the update of the current currentDate with upsert = true:

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

Now it will generate an objectid on the application server instead of a date / time (unless you use the raw command).

  1. Use the new timestamp or date object directly:

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

, , mondodb, , . , , raw insert.

/ .

+3

$currentDate - , .

MongoDB,

var current_date=new Date();
db.collection.insert({datefield:current_date})

new Date()

JavaScript Date, , , , , ,

0

All Articles