Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

mongodb - How to get the document with max value for a field with map-reduce in pymongo?

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 

An example document that look like these:

{ 
    "_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." 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use find_one to find the doc with the maximum uid by sorting on that field descending:

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

or using the defined constant:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...