Is there a simple way to fetch records from the last N days in MongoDB?

mongodb

Solution

Mongo doesn't have a symbolic date like SQL `NOW()` which you can use on the client and have evaluated on the server.

The best way to solve your problem is to evaluate calculate the dates on the client. In your specific case, since records aren't created in the future, likely you only need to calculate "now minus 7 days" in your client, and put that date in your query.

Sort of an aside, if you need the exact date from the server, you can fetch it like this:

db.eval( function() { return new Date() } ); 

Using most of the drivers you should be able to accomplish that using the `$eval` command.

Finally, you could accomplish this entirely on the server using a `where()` expression. However, I don't recommend this approach. Such queries can't take advantage of indexes and therefore must deserialize every record in the collection. They're very slow unless your collection is tiny. If you want to take this approach, though, you can use `new Date()` in the JavaScript for your `where()` expression.

Problem

If my records have a created_date field, is there a simple way to fetch all records that were created within the 7 days without calculating and adding the start and end date manually?

Original source