如何正确编写此查询

How to properly write this query

使用 pymongo v2.6,编写具有这些条件的查找查询的正确方法是什么:

select * from tasks where processed = 0 AND (process_lock_date is null or process_lock_date < now - 10 minutes) order by date_added asc limit 50

基本上需要将查询写入 select 50 条尚未被处理器拾取或尚未处理但超过 10 分钟前被拾取的记录(即拾取未处理的任务很久以前被拾取并且没有被标记为已处理以防以前的处理器出现故障)

感谢任何帮助。谢谢你。

您需要先导入 timedelta 和 datetime 对象以创建一个表示 10 分钟前的日期时间的日期对象,使用该对象为您 mongodb 查询如下:

from datetime import timedelta 

date = datetime.datetime.now() - datetime.timedelta(minutes=10)
docs = db.collection.find(
    {
        'processed': 0,
        '$or': [
            {'process_lock_date': {'$lt': date}},
            {'process_lock_date': null}
        ]
    }).sort({'date_added': 1}).limit(50)

for doc in docs:
    print(doc)