Search code examples
pythonmongodbpymongo

How I can find closest date by single request using pymongo? Date should be closest to Current Date


Dataset :

{"_id":{"$oid":"61e038a052124accf41cb5e4"},"event_date":{"$date":{"$numberLong":"1642204800000"}},
"name":"UFC Fight Night","event_url":"https://www.tapology.com/fightcenter/events/82805-ufc-fight-night","location":"Las Vegas, NV"}
{"_id":{"$oid":"61e038a252124accf41cb5e5"},"event_date":{"$date":{"$numberLong":"1642809600000"}},"name":"UFC 270","event_url":"https://www.tapology.com/fightcenter/events/82993-ufc-270","location":"Anaheim, CA"}
{"_id":{"$oid":"61e038a252124accf41cb5e6"},"event_date":{"$date":{"$numberLong":"1644019200000"}},"name":"UFC Fight Night","event_url":"https://www.tapology.com/fightcenter/events/83125-ufc-fight-night","location":"Las Vegas, NV"}

I'm using python, and that means I have no way to use $commands in my code for Mongo DB to find collection I need. Question is how can find object which should have datetime value closest to current date. As I understand I have to use python's datetime.now() to set current date and compare it ($currentDate doesn't work for Python). But but in order to compare values I have to deserialize the object and this looks very heavy. By default Mongo uses ISO datetime type.
Can you help me? At least direction to put me on a right way?


Solution

  • Here is a solution with an aggregate

    db.collection.aggregate([
      {
        "$addFields": {
          "dateDiff": {
            "$abs": {
              "$subtract": [
                "$event_date",
                {
                  "$literal": new Date()
                }
              ]
            }
          }
        }
      },
      {
        "$sort": {
          "dateDiff": 1
        }
      }
    ])
    
    • I use $subtract to have a difference between event_date and today.
    • $abs is to have the absolute value. To have the closest in the future or in the past.
    • And then we just have to sort by dateDiff

    In your code you have to replace new Date()

    Try it here