如何在pymongo中获取具有map-reduce字段最大值的文档? [英] How to get the document with max value for a field with map-reduce in pymongo?
本文介绍了如何在pymongo中获取具有map-reduce字段最大值的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 pymongo 中使用 map-reduce 找到具有最大 uid
字段的文档?
How do I find the document with the maximum uid
field with map-reduce in pymongo?
我尝试了以下方法,但打印出空白:
I have tried the following but it prints out blanks:
from pymongo import Connection
from bson.code import Code
db = Connection().map_reduce_example
db.things.insert({
"_id" : "50f5fe8916174763f6217994",
"deu" : "Wie Sie sicher aus der Presse und dem Fernsehen wissen, gab es in Sri Lanka mehrere Bombenexplosionen mit zahlreichen Toten.
",
"uid" : 13,
"eng" : "You will be aware from the press and television that there have been a number of bomb explosions and killings in Sri Lanka."
})
db.things.insert({
"_id" : "50f5fe8916234y0w3fvhv234",
"deu" : "Ich bin schwanger foo bar.
",
"uid" : 14,
"eng" : "I am pregnant foobar."
})
db.things.insert({
"_id" : "50f5fe8916234y0w3fvhv234",
"deu" : "barbar schwarz sheep, haben sie any foo
",
"uid" : 14,
"eng" : "barbar black sheep, have you any foo"
})
m = Code("function () {emit(this.uid,{'uid':this.uid,'eng':this.eng})}")
r = Code("function (key, values) {var total = 0;for (var i = 0; i < values.length; i++) {total += values[i];}return total;}")
result = db.things.inline_map_reduce(m, r)
for r in result:
print
如下所示的示例文档:
{
"_id" : ObjectId("50f5fe8916174763f6217994"),
"deu" : "Wie Sie sicher aus der Presse und dem Fernsehen wissen, gab es mehrere Bombenexplosionen mit zahlreichen Toten.
",
"uid" : 13,
"eng" : "You will be aware from the press and television that there have been a
number of bomb explosions and killings."
}
推荐答案
可以使用find_one
通过对该字段降序排序来查找具有最大 uid
的文档:
db.things.find_one(sort=[("uid", -1)])
或使用定义的常量:
db.things.find_one(sort=[("uid", pymongo.DESCENDING)])
这篇关于如何在pymongo中获取具有map-reduce字段最大值的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文