2013-01-21 16 views
5

Come si trova il documento con il campo massimo uid con riduci mappa in pymongo?Come ottenere il documento con valore massimo per un campo con riduci mappa in pymongo?

ho provato quanto segue ma esso stampa gli spazi:

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 

un documento di esempio che assomigliano a questi:

{ 
    "_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 nero pecore, avete qualsiasi foo' sarebbe' schwarzes Barbar Schaf, hast du etwas foo' in tedesco. – luckydonald

risposta

31

È possibile utilizzare find_one per trovare il doc con la massima uid da ordinamento su quel campo decrescente:

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

o utilizzo la costante definita:

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

non è più costoso fare 'find()' o 'find_one()' senza la mappa ridotta, specialmente quando ho quasi 2.000.000 di documenti nel database. – alvas

+1

No, ma vorresti comunque assicurarti di avere un indice su "uid" se hai bisogno che questo sia performante. – JohnnyHK

+2

Yo può utilizzare costanti predeterminate più descrittive per puntare all'argomento di direzione: 'pymongo.DESCENDING' invece di' -1' e 'pymongo.ASCENDING' invece di' 1' – userlond