Home > Net >  How to compare dates from MongoDB object in python?
How to compare dates from MongoDB object in python?

Time:12-15

I am trying to work out the difference in years between a MongoDB object and Today's date. The MongoDB object looks like this:

Key: Value

club_joined: 2021-08-10T00:00:00.000 00:00

I have the python code (that works):

loyal_players = []

for player in players.find():
    # get time players have been at club
    current_date = datetime.today()
    joined_club = player['club_joined']

    time_at_club = relativedelta(current_date, joined_club)
    time_at_club_years = time_at_club.years

    # check if they are over 10 years
    if time_at_club_years >= 10:
        loyal_players.append(player['short_name'])

But what I want is a Mongo query that can add into the .find() line:

for player in players.find():

I know the logic behind it is:

for player in players.find(
    where (
        (todayDate - player['club_joined']) > 10
    ):

But how do I write this as a MongoDB query in python?


MongoDb Type:

enter image description here

CodePudding user response:

The $subtract function will take 2 dates and return the diff in millis so this works:

    from pymongo import MongoClient
    import datetime

    now = datetime.datetime.now()

    TARG = 86400 * 1000 * 365 * 10 # secs in day X millis X 365 days X 10 yrs                            

    cursor = db.foo.aggregate([
        {"$match": {"$expr": {"$gt": [ {"$subtract": [now,"$club_joined"]}, TARG ] } }}
    ])
    for doc in cursor:
        print(doc)

CodePudding user response:

Using relativedelta seems simpler:

import datetime
from dateutil.relativedelta import relativedelta

dt = datetime.datetime.now() - relativedelta(years=10)

cursor = db.foo.find({'club_joined': {'$lt': dt}})

for doc in cursor:
    print(doc)
  • Related