0

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

Ax M
  • 330
  • 3
  • 15

1 Answers1

2

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)])
mintekhab
  • 203
  • 1
  • 3
  • Thank you! But now how do I actually assign to a variable the first value that it founds (since it sorts in descending)(sorry if I am noob ) – Ax M May 03 '18 at 18:13
  • You could return the value without assigning to variable `db.prob.find_one(sort=[("nr",pymongo.DESCENDING)])['nr']` – mintekhab May 05 '18 at 17:07