Reputation: 3264
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?
Upvotes: 4
Views: 3810
Reputation: 17218
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.
Upvotes: 3
Reputation: 636
Try something like this in the mongo console to return records created in the last 7 days (assuming created_date is the insertion date):
> startDate = new Date() // Current date
> startDate.setDate(startDate.getDate()-7) // Subtract 7 days
> startDate.setHours(0) // Set the hour, minute and second components to 0
> startDate.setMinutes(0)
> startDate.setSeconds(0)
> db.mycollection.find({created_date:{$gte: startDate}})
Quite a few lines of code, but at least you won't have to do date arithmetics.
Upvotes: 3