在mongodb ruby​​本地驱动程序中的Mapreduce

我正在使用mongodb的原生ruby驱动程序。我想用它执行map reducefunction,我试着按照这个链接在这里给出 。

undefined method last for nil:NilClass得到了错误状态的undefined method last for nil:NilClass

我尝试的代码是

 def self.mapreduce begin # remove old decoments DBEngine.remove_alldocuments(COLLECTION_MAPREDUCE) # sample collection insertion to perform map reduce function 3.times do |ctr| document = { "cust_id" => "A12", "amount" => 200, "status" => "S" } result = DBEngine.insert(COLLECTION_MAPREDUCE,document) puts result end 2.times do |ctr| document = { "cust_id" => "A13", "amount" => 250, "status" => "S" } result = DBEngine.insert(COLLECTION_MAPREDUCE,document) puts result end @map = "function(){" + "emit(this.cust_id,this.amount);" + "}; " @reduce = "function(key,values){" + "return Array.sum(values);" + "}" @query = { :query => { "status" => "S" } } result = COLLECTION_MAPREDUCE.map_reduce(@map,@reduce,@query) puts result rescue Exception => e puts e end end 

如何实现这一点。我是ruby和mongodb的新学习者。 请帮我。

我想出了原因,我的新代码是

 # Map function which emits the two necessary fileds like key and value to perform our operations map = "function(){" + "emit(this.cust_id,this.amount);" + "}; " # Reduce function reduces the values as per logic and outputs with key and value reduce = "function(key,values){" + "return Array.sum(values);" + "}" # Check this link fore reference :- http://www.rubydoc.info/github/mongodb/mongo-ruby-driver/master/Mongo/Collection:map_reduce # a customizable set of options to perform map reduce functions opts = { :query => { "status" => "S" }, # out specifies where we need to output the map reduce output. # if we specify simply a name in string like "order_totals" it creates a collection in that name # and stores in that # if we need to store in a temp memory and needed as output we need to give {:inline => 1} ans # :raw => true # check link :- http://docs.mongodb.org/manual/reference/command/mapReduce/#mapreduce-out-cmd :out => {:inline => 1}, :raw => true } result = COLLECTION_MAPREDUCE.map_reduce(map,reduce,opts) result["results"].each do |obj| puts obj puts "\n ------------" end 

在opts我需要给出out和raw.i来自这里的链接

这段代码工作正常。 谢谢。