pythonmongodbflaskpymongoflask-pymongo

Highest value(max) from mongodb collection error - Flask Python


I am trying to get the highest value for nr from a mongo database collection named prob that looks like this for now:

{
    "_id": {
        "$oid": "5ae9d062f36d282906c59736"
    },
    "nr": 1,
    "nume": "numeunu",
    "enunt": "-",
    "datedeintrare": "-",
    "datedeiesire": "-"
}
{
    "_id": {
        "$oid": "5ae9f190f36d282906c5b461"
    },
    "nr": 2,
    "nume": "numedoi",
    "enunt": "-",
    "datedeintrare": "-",
    "datedeiesire": "-"
}

My testing flask code is:

@app.route('/test')
def testaree():
    prob = mongo.db.prob
    return prob.find().sort({"nr":-1}).limit(1)

but it gives me an error TypeError: if no direction is specified, key_or_list must be an instance of list


Solution

  • The syntax for sorting using pymongo is different from the mongo query language. In the above code the expression used is

    sort({"nr":-1})
    

    However , that is a mongo shell query syntax. When using pymongo it should be

    sort("nr", pymongo.DESCENDING)
    

    You could also use find_one instead of a limit clause once the data is sorted.

    db.prob.find_one(sort=[("nr", pymongo.DESCENDING)])