How to properly increase the number of dates in mongoDB?

Not being a particularly strong Javascript guy, I have a bit of trouble trying to update many Date objects in Mongo.

It seems that $inc is not yet implemented for Date objects . So, to try and pounce on a bunch of dates for a day, I called (something like this) a script from bash via mongo myScript.js :

 conn = new Mongo(); db = conn.getDB('myDatabase'); var incrementDates = function() { db.blah.find(myQuery).forEach(function(doc) { db.blah.update( { _id : doc._id , my_date : { $exists : true } } , { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }} ); }); } incrementDates(); 

The main idea seems to work quite well in the mongoDB shell:

 > var doc = db.blah.findOne(myQuery) > doc.my_date ISODate("1962-11-02T23:00:00Z") > new Date(doc.my_date.getTime() + 86400000); ISODate("1962-11-03T23:00:00Z") 

But not so good in the script:

 TypeError: doc.my_date has no properties 

So, I believe that I am trying to call getTime on null somewhere, even if the request in my update should only return documents where my_date exists.

Any ideas on what's going on here? More importantly: is there a better way to do this?

+6
source share
1 answer

The problem is that my $exists request (obviously at a second glance) is in the wrong place. Documents were returned which, of course, did not include my_date .

Here is a fixed feature that works as expected.

 var incrementDates = function() { db.blah.find({ ... , my_date : { $exists : true } ).forEach(function(doc) { db.blah.update( { _id : doc._id } , { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }} ); }); } 
+6
source

Source: https://habr.com/ru/post/953686/


All Articles