21

I am setting a cron job to collect results from MongoDB database profiler. I'd like to collect results within a 24 hrs period. I plan to run mongo command with javascript.

Question is, in Mongo shell, how do I write a query to find a date range from 24 hrs ago? Such as:

db.system.profile.find({
    "timestamp" : {
        $lte : <current date & time>,
        $gt : <date & time 24 hrs ago>
    }
})

3 Answers 3

46

Found answer here: https://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript

db.system.profile.find({ 
  "timestamp" : { 
    $lt: new Date(), 
    $gte: new Date(new Date().setDate(new Date().getDate()-1))
  }   
})
1
  • 1
    Works in Compass but i cant get it to work in Atlas.
    – djangofan
    Dec 7, 2021 at 20:31
6
db.system.profile.find({ 
 "timestamp" : 
    {     
        $gte:   new Date(new Date().setHours(00,00,00)) ,     
        $lt :  new Date(new Date().setHours(23,59,59)) 
   } 
})
2
  • 4
    Please explain what your code does and how it is different from the code seen in the accepted answer.
    – dezso
    Aug 31, 2018 at 7:50
  • 1
    This differs from the accepted answer in that it searches for the whole current day (eg. "Friday"). Conversely, the accepted answer searches for "the last 24 hours". Apr 17, 2020 at 21:54
1
db.collection.find(
        {$and: 
                [
                { "status.code":"DELIVERY_PENDING"},
                {"status.createdDtm": {$lte: new Date().getTime()-(1*60*60*1000) }}
                ]

        }
        )
2
  • You should add details about how this works and why it fixes the problem.
    – Hannah Vernon
    Aug 31, 2018 at 14:16
  • 1
    What's with "DELIVERY_PENDING"?! May 23, 2019 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.