Jul 28, 2016

Add day to ISODate in MongoDB

We can use $add operator to add days in ISODate in mongodb, $add is the Arithmetic Aggregation Operator which adds number and date in mongodb.

Syntax:


{ $add: [ <expression1>, <expression2>, ... ] }


Note:  If one of the argument is date $add operator treats to other arguments as milliseconds to add to the date.

Example: Suppose we have a Test collection as below.


{"Title" : "Add day to ISODate in MongoBD","CreatedDate" : ISODate("2016-07-07T08:00:00.000Z")}


Query to add 2 days in CreatedDate


db.Test.aggregate([
     { $project: { Title: 1, AddedDate: { $add: [ "$CreatedDate", 2*24*60*60000 ] } } }
   ])


Result:


{ "_id" : ObjectId("579a1567ac1b3f3732483de0"), "Title" : "Add day to ISODate in MongoBD", "AddedDate" : ISODate("2016-07-09T08:00:00.000Z") }


Note: As mentioned in above note we have to convert days in millisecond because $add operator treat to other argument as milliseconds if one of them arguments is date.

Add Minutes

We can add minute same as above, we need to convert minutes into milliseconds, see following query.


db.Test.aggregate([
     { $project: { Title: 1, AddedDate: { $add: [ "$CreatedDate", 10*60*1000 ] } } }
   ])


Result:



{ "_id" : ObjectId("579a1567ac1b3f3732483de0"), "Title" : "Add day to ISODate in MongoBD", "AddedDate" : ISODate("2016-07-07T08:10:00.000Z") }