Search code examples
mongodbsearchtimestampisodate

Search MongoDB collection when date is stored as timestamp


I'm new to MongoDB. I have a collection which has a field named time in it. It's in timestamp format like this:

{
        "_id" : "uniqueid_001",
        "customer_id" : 1234567,
        "time" : 1513300298028,
        "price" : 1000,
        "action" : "buy"
}

Now I would like to only retrieve documents between a date range. I've used something like this:

db.sales.find({
     time: {
          $gt: ISODate("2018-02-01T00:00.000Z")/1000,
          $lt: ISODate("2018-02-10T00:00.000Z")/1000
     } 
})

But this won't work. Anyone has any idea that how may I achieve this?

Thanks

P.S. This question is somehow answered here: Find objects between two dates MongoDB but there's a difference that date is saved in ISO format on that question but I need to compare dates in timestamp format.


Solution

  • Oops! Find it myself... The timestamp is saved in collection in 13 digits format. It didn't need /1000 instead /1 in the end of ISODate function:

    db.sales.find({
         time: {
              $gt: ISODate("2018-02-01T00:00.000Z")/1,
              $lt: ISODate("2018-02-10T00:00.000Z")/1
         } 
    })
    

    Thanks anyway