2013-01-21 37 views
5

如何使用pymongo中的map-reduce找到最大uid字段的文檔?如何使用pymongo中的map-reduce爲字段獲取最大值的文檔?

我曾嘗試以下,但它打印出空白:

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." 
} 
+1

順便說一句,'BARBAR黑羊,你有什麼foo'會'BARBAR schwarzes Schaf,竟杜某物foo'在德國。 – luckydonald

回答

31

您可以使用find_one找到與最大uid由DOC在該字段下降排序:

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

或使用定義的常量:

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

在沒有簡化映射的情況下執行'find()'或'find_one()'並不是更加昂貴,特別是當我在數據庫中有近2,000,000個文檔時。 – alvas

+1

不,但如果你需要這個功能,你仍然想確保你有一個'uid'的索引。 – JohnnyHK

+2

喲可能會使用更多的描述性預變化常量來指向方向參數:'pymongo.DESCENDING'而不是'-1'和'pymongo.ASCENDING'而不是'1' – userlond

相關問題