Adding/Subtracting days to ISODate in MongoDB Shel

2019-03-15 00:00发布

I have a query where I need to get events that are one day before or after from a specific date. I need to add or subtract one day to that ISODate variable. Here is my query :

db.event.find().forEach( function (x) {

  print("x : " + x.EventID + ", " + x.ISODate); 
  db.events.find( {
   "$or" : [{
       "StartDate" : { "$gte" : x.ISODate } // Here i need to subtract one day
       }, {
           "EndDate": { "$lt" : x.ISODate} // Here i need to add one day
           }]
}).forEach(function(otherDay) {
        print("x.EventID : " + x.EventID + ", other.Date : " + otherDay.StartDate + " - " + otherDay.EndDate);
      });

});

How can i add or subtract days to an ISODate variable in mongodb shell?

标签: mongodb shell
2条回答
你好瞎i
2楼-- · 2019-03-15 00:12

Not an exact answer but related.

I needed to increment a date field for all items in the mongodb collection. Use minus if you need to subtract.

The query below will add 1 day to myDateField in myCollection.

db.myCollection.find().snapshot().forEach(
    function (elem) {
        db.myCollection.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    myDateField: new Date(elem.myDateField.getTime() + 1*24*60*60000)
                }
            }
        );
    }
);

1 day = 1*24*60*60000 = 1 x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
查看更多
叼着烟拽天下
3楼-- · 2019-03-15 00:29

This has been answered on Query to get last X minutes data with Mongodb

query = {
    timestamp: { // 18 minutes ago (from now)
        $gt: new Date(ISODate().getTime() - 1000 * 60 * 18)
    }
}

And in your case, for a number of days:

"StartDate" : { "$gte" : new Date(ISODate().getTime() - 1000 * 3600 * 24 * 3) }

or

"StartDate" : { "$gte" : new Date(ISODate().getTime() - 1000 * 86400 * 3) }

(here the 3 is your number of days)

查看更多
登录 后发表回答