PyMongo聚合不与$ max运算符一起使用

时间:2020-05-29 13:17:18

标签: python mongodb pymongo flask-pymongo

我的查询在mongo shell上运行良好。但是当通过pymongo运行时给出错误。有人可以帮我吗?

db.collectioname.aggregate([
     {   "$match": { "$and": [ 
                        { "organization_id": int(organization_id) }, 
                        { "resulttime":{
                                "$gte":stdate,                                          
                                "$lte":enddate  
                            } 
                        }
                    ] 
            }
    },
    { "$skip" : int(offset) },
    { "$limit" : int(limit) }, 
    { "$group": { 
        "_id": "$userid",
        "max_temperature": { "$max": "$temperature" }, 
        "min_temperature": { "$min": "$temperature" } 
    }}
     ])

但是,我得到一个错误

pymongo.errors.OperationFailure: unknown operator: $max

1 个答案:

答案 0 :(得分:1)

我尝试过;这对我来说可以。您可以确认此示例代码有效吗?如果没有打印出完整的堆栈跟踪。

import pymongo
import datetime

offset = 0
limit = 1
organization_id = 1
stdate = datetime.datetime(2020, 1, 1, 0, 0)
enddate = datetime.datetime(2021, 1, 1, 0, 0)

db = pymongo.MongoClient()['mydatabase']
db.collectioname.insert_one({'organization_id': organization_id, 'resulttime': datetime.datetime.now(), 'temperature': 37.4})

records = db.collectioname.aggregate([
    {"$match": {"$and": [
        {"organization_id": int(organization_id)},
        {"resulttime": {
            "$gte": stdate,
            "$lte": enddate
        }}]}
    },
    {"$skip": int(offset)},
    {"$limit": int(limit)},
    {"$group": {
        "_id": "$userid",
        "max_temperature": {"$max": "$temperature"},
        "min_temperature": {"$min": "$temperature"}
    }}
])

print(list(records))