Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Mongo results from one month ago

Tags:

mongodb

I have around 30-40 records like the example before in my database and I'm looking to get the notifications that are less than 1 month old (from today's date). Is there a way in Mongo to get these results without having to pass in a today's date via JavaScript? Or if I do have to pass it in via JavaScript, how would I process this against my created date?

{
    "_id" : ObjectId("48445b4dc72153e9ad7f3bfb"),
    "notificationID" : "78723asd5-vnbb-xv31-afe0-fa9asf164e4",
    "notification" : "Notification #1",
    "created" : ISODate("2016-11-21T20:33:53.695Z")
}

Any help is appreciated, thanks.

like image 756
Paul Ness Avatar asked Oct 27 '25 02:10

Paul Ness


1 Answers

MongoDB has its own Javascript interpreter so, unless your MongoDB server has a different date than your system, it knows the current date so you easily use simple Javascript to compute the value you're looking for using a regular Date object and use it in your query.

var d = new Date();
d.setMonth(d.getMonth() - 1); //1 month ago
db.data.find({created:{$gte:d}}); //change "data" for your collection's name

If you need a different date than your database's, I'm afraid you'll have to somehow pass it as a parameter.

like image 199
SolarBear Avatar answered Oct 29 '25 10:10

SolarBear