How do I add days to the current date field to be able to compare range of dates

Viewed 554

I need to do the following MySql approach in MongoDB:

SELECT * FROM table T WHERE DATE_ADD(T.createdAt, INTERVAL 2 DAY) > someDate;

I was thinking on aggregations, expressions, Etc., but I couldn't find a way to approach this.

Thanks in advance!

2 Answers

You may use $add here:

db.yourCollection.find({
    "createdAt": { $gt: { $add: [ "$someDate", -1000 * 3600 * 24 * 3 ] } }
});

The above assumes that both fields createdAt and someDate are ISO timestamps. Note that I have actually rephrased your query as follows, so that createdAt appears by itself on the LHS of the inequality:

SELECT *
FROM yourTable
WHERE createdAt > someDate - INTERVAL 2 DAY;

When you have to work with date/time values then I recommend the moment.js library. Would be this one:

db.collection.find({
   createdAt: { $gte: { moment().subtract(2, 'days').toDate() } } 
})
Related