I am trying to assign to a variable the value of nr
from the first value of the Cursor object named items
in my code (which is the max of nr
) but I don't know how to do that.(I am using flask pymongo. I saw a question similar to mine but it doesn't work for me since I am using a different database).
This is my code:
@app.route('/testaree')
def testaree():
prob = mongo.db.prob
items = prob.find().sort("nr", pymongo.DESCENDING)
return flask.jsonify(items)
My database prob
looks like this (I am tring to assign to a variable the value of the biggest nr
from the db collection):
{
"_id": {
"$oid": "5ae9d062f36d282906c59736"
},
"nr": 1,
"nume": "numeunu",
"enunt": "-",
"datedeintrare": "-",
"datedeiesire": "-"
}
{
"_id": {
"$oid": "5ae9f190f36d282906c5b461"
},
"nr": 2,
"nume": "numedoi",
"enunt": "-",
"datedeintrare": "-",
"datedeiesire": "-"
}
You can use limit()
so that the database only returns the first result, and access the first element in the list.
items = prob.find().sort("nr", pymongo.DESCENDING).limit(1)
return flask.jsonify(items[0])
EDIT: You can get the nr
property as follows. Note that the type of nr
will depend on the type that is stored in mongo. In your comment you are JSON encoding the int so it will be converted to a string.
items = prob.find().sort("nr", pymongo.DESCENDING).limit(1)
nr_prop = items[0]["nr"]
print(nr_prop)
flask.jsonify(nr_prop)
Or if nr
is not an int
(which it should be from looking at the data in your question) in the database:
nr_prop = int(items[0]["nr"])
print(nr_prop)
flask.jsonify(nr_prop)