我想实现对 message 表 sr_ids 字段的 group 查询,网上搜索了一些解决方法,但是有点看不懂,求教了。
可能需要使用 map-reduce 完成,这种事情不是 nosql 的强项。
def group_by(field) map = %Q{ function() { emit(this.#{field}, { count: 1 }); } } reduce = %Q{ function(key, values) { var result = { count: 0 }; values.forEach(function(value) { result.count += value.count; }); return result; } } result = self.map_reduce(map, reduce).out(inline: true).to_a hash = {} result.each do |r| hash[r["_id"]] = r["value"]["count"].to_i end #hash.sort_by{|_k, v| v}.to_h #Hash[*hash.sort_by{|_k, v| v}.flatten] hash.sort_by(&:last).to_h end
#1 楼 @debugger 我遇到failed with error 16052: "exception: could not create cursor over th_test.messages for query : {} sort : { created_at: -1 }"这个错误,未找到解决方案请教一下是哪里有错?
failed with error 16052: "exception: could not create cursor over th_test.messages for query : {} sort : { created_at: -1 }"
def messages map = %Q{ function() { emit(this.sr_flag, { count: 1 }); } } reduce = %Q{ function(key, values) { var result = { count: 0 }; values.forEach(function(value) { result.count += value.count; }); return result; } } result = Message.map_reduce(map, reduce).out(inline: true).to_a result # Message.or(receiver_document_id: "#{self.id}", :recipient_delete.ne=>true).or(sender_document_id: "#{self.id}", :sender_delete.ne=>true).desc(:created_at) end