pythonmongodbpymongoflask-pymongo

PyMongo aggregation Not working with $max operator


My query is working fine on the mongo shell. But when running through pymongo is giving error. Can someone help me with this one.

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" } 
    }}
     ])

However, I am getting an error as

pymongo.errors.OperationFailure: unknown operator: $max

Solution

  • I tried it; it works fine for me. Can you confirm this sample code works. If not print a full stack trace.

    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))