Question: Not being a particularly strong Javascript guy, I'm having a bit of trouble trying to update a lot of `Date` objects in Mongo.

It seems that [`$inc` has not yet been implemented for `Date` objects](https://jira.mongodb.org/browse/SERVER-3174). So, to try and bump a bunch of dates by a day, I called (something like) this 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 basic idea seems to work well enough 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 well in the script:

```
TypeError: doc.my_date has no properties

```

So I take it that I'm trying to call `getTime` on a `null` somewhere, even though the query in my update should only return documents where `my_date` exists.

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

Answer: 
The problem is that my `$exists` query is (obviously, on second look) in the wrong place. Documents were being returned that, surely enough, didn't include `my_date`.

Here's the patched up function, which 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) }}
    );
  });
}

```
Starting in `Mongo 5.0`, it's a nice use case for the new [`$dateAdd`](https://docs.mongodb.com/v5.0/reference/operator/aggregation/dateAdd/#mongodb-expression-exp.-dateAdd) aggregation operator:

```
// { "date" : ISODate("2020-04-05T07:14:17.802Z"), "x" : "y" }
db.collection.updateMany(
  { date : { $exists : true } },
  [{ $set: { date: { $dateAdd: { startDate: "$date", unit: "day", amount: 1 } } } }]
)
// { "date" : ISODate("2020-04-06T07:14:17.802Z"), "x" : "y" }

```

* The first part `{ date : { $exists : true } }` is the match query, filtering which documents to update (in our case all documents having the `date` field).
* The second part `[{ $set: { date: { $dateAdd: { startDate: "$date", unit: "day", amount: 1 } } } }]`, updates the value of the `date` field by adding (`$dateAdd`) `1` (`amount`) `day` (`unit`) to `$date` (`startDate`).