简体   繁体   English

如何在烧瓶pymongo中将光标对象的第一个值赋给变量

[英]How to assign to a variable the first value of the cursor object in flask pymongo

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). 我正在尝试从我的代码中名为items的Cursor对象的第一个值(这是nr的最大值)中为变量分配nr的值,但是我不知道该怎么做。(我正在使用flask pymongo我看到了一个与我的问题类似的问题,但由于我使用的是其他数据库,因此该问题对我不起作用。

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): 我的数据库prob如下所示(我正试图将db集合中最大nr的值分配给一个变量):

{
    "_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. 您可以使用limit()以便数据库仅返回第一个结果,并访问列表中的第一个元素。

items = prob.find().sort("nr", pymongo.DESCENDING).limit(1)
return flask.jsonify(items[0])

EDIT: You can get the nr property as follows. 编辑:您可以获取nr属性,如下所示。 Note that the type of nr will depend on the type that is stored in mongo. 请注意, nr的类型取决于mongo中存储的类型。 In your comment you are JSON encoding the int so it will be converted to a string. 在您的注释中,您使用JSON编码int,因此它将被转换为字符串。

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不是数据库中的int (应该是通过查看问题中的数据而得出的),则:

nr_prop = int(items[0]["nr"])
print(nr_prop)
flask.jsonify(nr_prop)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM