【问题标题】:How to get the document with max value for a field with map-reduce in pymongo?如何在pymongo中获取具有map-reduce字段最大值的文档?
【发布时间】:2013-01-04 04:00:04
【问题描述】:

如何在 pymongo 中使用 map-reduce 找到具有最大 uid 字段的文档?

我尝试了以下方法,但打印出空白:

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.\n", 
    "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.\n", 
    "uid" : 14, 
    "eng" : "I am pregnant foobar." 
})

db.things.insert({  
    "_id" : "50f5fe8916234y0w3fvhv234", 
    "deu" : "barbar schwarz sheep, haben sie any foo\n", 
    "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.\n", 
    "uid" : 13, 
    "eng" : "You will be aware from the press and television that there have been a 
             number of bomb explosions and killings." 
}

【问题讨论】:

  • 顺便说一句,barbar black sheep, have you any foo 在德语中将是 barbar schwarzes Schaf, hast du etwas foo

标签: mongodb mapreduce field max pymongo


【解决方案1】:

您可以使用find_one 查找具有最大uid 的文档,方法是按该字段降序排序:

db.things.find_one(sort=[("uid", -1)])

或使用定义的常量:

db.things.find_one(sort=[("uid", pymongo.DESCENDING)])

【讨论】:

  • 如果没有缩小的地图,做find()find_one() 不是更昂贵,尤其是当我在数据库中有接近2,000,000 个文档时。
  • 不,但如果您需要它的性能,您仍然需要确保在 uid 上有一个索引。
  • 你可以使用更具描述性的预定义常量来指向方向参数:pymongo.DESCENDING 而不是 -1pymongo.ASCENDING 而不是 1
猜你喜欢
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 2021-12-22
相关资源
最近更新 更多