[英]pymongo sort and find_one issue
I am trying to sort a collection called user_score
using the key position
and get the very first document of the result.我正在尝试使用键
position
对名为user_score
的集合进行排序,并获取结果的第一个文档。 In this case the collection user_score
doesn't exist and I was hoping to get the result as None
, but i was getting a cursor back.在这种情况下,集合
user_score
不存在,我希望得到None
的结果,但我得到了 cursor 回来。
1. result = 1.结果=
db.user_score.find({'score':'$lt':score}}).sort("position,pymongo.DESCENDING").limit(1)
Now i changed my query like below and did not get anything as expected.现在我像下面这样更改了我的查询,但没有得到预期的任何结果。
2. result = 2.结果=
db.user_score.find_one({'score':{'$lt':score}}, sort=[("position", pymongo.DESCENDING)])
What's the problem with my first query?我的第一个查询有什么问题?
Thanks谢谢
A little late in my response but it appears that the current version of PyMongo does support a sort operation on a find_one call.我的回复有点晚,但似乎当前版本的 PyMongo 确实支持对 find_one 调用的排序操作。
From the documentation page here (please grep the section for find_one):从这里的文档页面(请 grep find_one 部分):
All arguments to find() are also valid arguments for find_one(), although any limit argument will be ignored.
find() 的所有 arguments 对 find_one() 也是有效的 arguments,尽管任何限制参数都将被忽略。 Returns a single document, or None if no matching document is found.
返回单个文档,如果找不到匹配的文档,则返回 None。
Example usage is as follows:示例用法如下:
filterdict = {'email' : 'this.is@me.com'}
collection.find_one(filterdict, sort=[('lastseen', 1)])
Hope this helps more recent searchers!希望这有助于更多最近的搜索者!
In your first query, in the sort function you're passing one argument ("position,pymongo.DESCENDING")
, when you should be passing two arguments ("position", pymongo.DESCENDING)
.在您的第一个查询中,在排序 function 中,您传递一个参数
("position,pymongo.DESCENDING")
,而您应该传递两个 arguments ("position", pymongo.DESCENDING)
。
Be sure to mind your quotation marks.一定要注意你的引号。
This is the default mongodb behavior on find.这是查找时的默认 mongodb 行为。 Whenever you use
find
you get a list of the result (in this case an iterable cursor).每当你使用
find
时,你都会得到一个结果列表(在本例中是一个可迭代游标)。 Only findOne
- or it's PyMongo equivalent find_one
will return None
if the query has no matches.如果查询没有匹配项,只有
findOne
- 或者它是 PyMongo 等效的find_one
将返回None
。
Use list to convert the value of the cursor into a dict:使用列表将 cursor 的值转换为字典:
list(db.user_score.find({'score':'$lt':score}}).sort("position",pymongo.DESCENDING).limit(1))[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.