Query mongo for records older/newer than last N days

Let’s assume you are querying a collection named ‘users’ and you want to see users created before of after the last ’n’ days, it can seem tricky, but it doesn’t have to be.

A simple query can solve your problem

For users created before ’n’ days:

db.users.find({"dateInserted":{$lt:new Date(Date.now() - 24*60*60 * n * 1000)}})

 

For users created AFTER ’n’ days:

db.users.find({"dateInserted":{$gt:new Date(Date.now() - 24*60*60 * n * 1000)}})