0

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

5
  • Double checking: is club_joined an ISO8601 string? Not a real mongodb datetime? Commented Dec 14, 2021 at 18:33
  • @BuzzMoschetti no, it is a Date, I will add a screenshot to my question to show Commented Dec 14, 2021 at 18:43
  • @RC07JNR Would you be able to just covert to timestamp milliseconds and take the difference, and calculate the days/months/years? Or would that be too consuming for your app (after querying the data) Commented Dec 14, 2021 at 18:49
  • @Jacob If that can be added into the .find() of the MongoDD line that would probably work but I'm not sure how to do that! Commented Dec 14, 2021 at 18:50
  • @RC07JNR stackoverflow.com/questions/35852223/query-mongo-on-timestamp - Would this help? Commented Dec 14, 2021 at 18:54

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I think this is along the right line! That gives me the following error tho: Unresolved attribute reference 'datetime' for class 'datetime'. My import = from datetime import datetime and the line is exactly what you have, any ideas?
I added the 2 imports to my answer as they appear in my working example. Don't be shy to accept the answer and upvote. ;-)
Aww amazing! Thank you so much
0

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)

1 Comment

It does. I am a\lways trying to demo the agg functions.
0

Following code with logic of expire time of 3 mintues of previously inserted data works fine.

today = datetime.today()
time_threshold = today - timedelta(minutes=3)


data = mongo_client[db_name][f'{instrument_name}'].find_one({
    "$or": [
        {
            "$and": [
                {"updated_at": {"$lt": time_threshold}},
                {"updated_at": {"$exists": True}},
            ]
        },
        {
            "$and": [
                {"generated": "Error"},
                {"updated_at": {"$exists": False}},
            ]
        },
    ],
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.