Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto populate date in MongoDB on insert

Tags:

mongodb

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 equivalent to this for insert operations?

like image 654
russoue Avatar asked Jun 13 '16 05:06

russoue


3 Answers

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.

like image 53
Maruf Maniruzzaman Avatar answered Oct 23 '22 08:10

Maruf Maniruzzaman


The $currentDate is an update operator which populates date field with current date through update operation.

To auto populate date field while insertion of new MongoDB document,please try executing following code snippet

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

In above code snippet the statement

new Date()

creates a new JavaScript Date object which consists of a year, a month, a day, an hour, a minute, a second, and milliseconds

like image 22
Rubin Porwal Avatar answered Oct 23 '22 08:10

Rubin Porwal


If you want to populate this value when running it in the server side, and are concerned about it being passed by the client, you can add properties to the data object that is being used in the insert statement only when it will be saved. This way, you can guarantee that it will be added every time with the server's date, not the client's:

Client side

...
let data = { info1: 'value1', info2: 'value2'}
someApi.addInfo(data);
...

Server side

function addInfo(data){
    ...
    data['creationDate'] = new Date();
    db.collection.insertOne(data);
    ...
}

Result will be:

{
    info1: 'value1', 
    info2: 'value2',
    creationDate: ISODate("2018-09-15T21:42:13.815Z")
}

If you are passing multiple values for insertion (using insertMany) you have to loop over the items and add this property for all of them.

You can also use this approach when updating documents if for some reason you can't use the $currentDate operator, just be sure you are not replacing any existing properties in the data passed to mongodb.

like image 1
c-chavez Avatar answered Oct 23 '22 08:10

c-chavez