Mongoid:通过ID数组查找 [英] Mongoid: find through Array of ids
本文介绍了Mongoid:通过ID数组查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经通过MapReduce提取了许多ID.我已经按照某些条件对这些ID进行了排序,现在我需要按照以下特定顺序来获取这些对象:
I've fetched a number of ids through MapReduce. I've sorted those ids by some criteria and now I need to get those objects in this particular order:
MyModel.find(ids)
对吗?但是它返回的对象不是按存储顺序ID的顺序.看起来和
Right? But it returns objects not in the order ids are stored. Looks like this is just the same as
MyModel.where(:_id.in => ids)
不会以与存储的id相同的顺序返回获取的对象.
which won't return fetched objects in just the same order as stored ids.
现在我可以做到
ids.map{|id| MyModel.find(id)}
这可以完成工作,但是会多次破坏数据库.
which will do the job but it will knock the database many many times.
推荐答案
在拥有所有对象之后,您可以手动进行排序.像这样:
You can do the ordering by hand after you have all your objects. Something like this:
ordering = { }
ids.each_with_index { |id, i| ordering[id] = i }
objs = MyModel.find(ids).sort_by { |o| ordering[o.id] }
这篇关于Mongoid:通过ID数组查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文