0

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": "-"
}
Ax M
  • 330
  • 3
  • 15

1 Answers1

1

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)
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
  • items[0] gives me the object it but how do I actually get the `nr` like I have in my db collection? – Ax M May 03 '18 at 20:45
  • EDIT: I figgured it out. I did `flask.jsonify(items[0]["nr"])` and than I assign it to a variable `numbers = flask.jsonify(items[0]["nr"])`. But the problem is that my variable is not an integer and I don't know how to make it an integer – Ax M May 03 '18 at 21:50
  • I have updated my answer to include `nr` and data types. – Jim Wright May 04 '18 at 08:01
  • I tried the same thing to convert it to an `int` but it gives me this error `TypeError: 'int' object is not callable`. Please help me. I tried so hard to solve it but I don't know how Edit: If I `return flask.jsonify(nr_prob)` it does work. But if I `return nr_prob` it gives me the error above – Ax M May 04 '18 at 08:04
  • Have you created a variable called `int`? – Jim Wright May 04 '18 at 08:08
  • 1
    You could also use [find_one](http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one), which is roughly equivalent to what you have here, but will have PyMongo return the first element directly, giving you slightly cleaner code. – dcrosta May 28 '18 at 19:32