2013-01-21 8 views
5

Jak znaleźć dokument o maksymalnym polu uid z map-reduce w pymongo?Jak uzyskać dokument z maksymalną wartością dla pola z mapą-zmniejszyć w pymongo?

Próbowałem następujących ale wypisuje wykroje:

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 

Przykładem dokumentów, które wyglądają jak te:

{ 
    "_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

btw, 'barbar black sheep, have you any foo' będzie' barbar schwarzes Schaf, hast du etwas foo' po niemiecku. – luckydonald

Odpowiedz

31

Można użyć find_one znaleźć doc z maksymalną uid przez sortowanie w tym polu malejącym:

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

lub za pomocą zdefiniowana stała:

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

nie jest droższe robić 'find()' lub 'find_one()' bez zmniejszonej mapy, szczególnie gdy mam blisko 2 000 000 dokumentów w bazie danych. – alvas

+1

Nie, ale nadal chcesz mieć pewność, że masz indeks na 'uid', jeśli chcesz, aby był wydajny. – JohnnyHK

+2

Yo może użyć większej liczby deskryptywnych stałych predykowanych do argumentu kierunku punktowego: 'pymongo.DESCENDING' zamiast' -1' i 'pymongo.ASCENDING' zamiast' 1' – userlond

Powiązane problemy