Home > front end >  mongodb extract data between dates saved with javascript Date.now
mongodb extract data between dates saved with javascript Date.now

Time:11-13

I have a mongodb collection called foo_collection where the documents contains a field called createdby that uses javascript Date.now() to save the timestamp.

an example would be

{
    "_id": {
        "$oid": "618a669ea3bff474f6fe4767"
    },
    "widgetid": "ddbae9a2-4156-11ec-905a-02cf95edae88",
    "publisher_id": "938ecebe-1089-11ec-8bd1-0a57868782b0",
    "impression_id": "b6bfc0bc-1dc4-11ec-850e-0a57868782b0",
    "logid": "ksaeqkqe65",
    "createdby": {
        "$numberLong": "1636460191573"
    }
}

As you can see the field createdby uses $numberLong to save the data.

And, According to the doc The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

How to query the collection foo_collection using pymongo such that I get the datas between two date range ?

CodePudding user response:

Since you are using Date.now() which returns a number and not a Date object you can simply do a number comparison

db.collection.find({
  $and: [
    {
      createdBy: {
        $gt: *some_number*
      }
    },
    {
      createdBy: {
        $lt: *some_number*
      }
    }
  ]
})```

CodePudding user response:

converting python datetime into timestamp here

start = datetime.strptime('2021-11-10', '%Y-%m-%d').timestamp() * 1000
end = datetime.strptime('2021-11-11', '%Y-%m-%d').timestamp() * 1000

db. collection.find({
  "createdby": {
    "$gt": start,
    "$lt": end
  }
})
  • Related