To increment a date, use setDate, getDate() and perform increment operation. Let us first create a collection with documents −
> db.demo168.insertOne({"DueDate":null}); { "acknowledged" : true, "insertedId" : ObjectId("5e3695ae9e4f06af551997d6") }
Display all documents from a collection with the help of find() method −
> db.demo168.find();
This will produce the following output −
{ "_id" : ObjectId("5e3695ae9e4f06af551997d6"), "DueDate" : null }
Following is the query to increment a date in JavaScript, in order to update MongoDB −
> var t = new Date(); > t.setDate(t.getDate()+1); 1580722089017 > > var dat = new Date(); > dat .setDate(dat .getDate()+2); 1580808489085 > > db.demo168.update( ... { "_id": ObjectId("5e3695ae9e4f06af551997d6") }, ... { ... "$currentDate": { "DueDate": true }, ... "$set": { ... "DueDate1": t, ... "DueDate2": dat ... } ... } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo168.find();
This will produce the following output −
{ "_id" : ObjectId("5e3695ae9e4f06af551997d6"), "DueDate" : ISODate("2020-02-02T09:28:09.308Z"), "DueDate1" : ISODate("2020-02-03T09:28:09.017Z"), "DueDate2" : ISODate("2020-02-04T09:28:09.085Z") }