2

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!

Ele
  • 33,468
  • 7
  • 37
  • 75
  • 1
    I think it’s no needed the sample document because my question is about the translation of that MySQL query into a Mongodb query. Basically, find the documents where the field `createdAt + days` is greater than `somedate`. – Ele Jan 16 '21 at 10:48
  • if you don't want to do this in query, you can minus 2 days from `someDate` in your client side. so just need to match only greater than condition in query. – turivishal Jan 16 '21 at 12:12

2 Answers2

3

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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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() } } 
})
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110