【发布时间】:2022-01-18 01:11:43
【问题描述】:
我正在尝试计算 MongoDB 对象和今天日期之间的年份差异。 MongoDB 对象如下所示:
Key: Value
club_joined: 2021-08-10T00:00:00.000+00:00
我有 python 代码(有效):
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'])
但我想要的是一个可以添加到 .find() 行的 Mongo 查询:
for player in players.find():
我知道它背后的逻辑是:
for player in players.find(
where (
(todayDate - player['club_joined']) > 10
):
但是如何在 python 中将其编写为 MongoDB 查询?
MongoDb 类型:
【问题讨论】:
-
双重检查:
club_joined是 ISO8601 字符串吗?不是真正的 mongodb 日期时间? -
@BuzzMoschetti 不,它是
Date,我将在我的问题中添加屏幕截图以显示 -
@RC07JNR 您能否仅转换为时间戳毫秒并获取差异,然后计算天/月/年?或者这对您的应用来说是否过于消耗(在查询数据之后)
-
@Jacob 如果可以将其添加到 MongoDD 行的
.find()中,这可能会起作用,但我不知道该怎么做! -
@RC07JNR stackoverflow.com/questions/35852223/query-mongo-on-timestamp - 这有帮助吗?