2017-08-02 98 views
0

我们在ruby on rails项目中使用mongoid,我需要一个简单的用户列表,按照用于查找正确结果集的ID进行排序。使用mongoid按照输入数组的顺序排序查询

所以基本上是这样的:

ids = [7, 1, 3] 
User.where(:uid.in => ids) 

这给出了一个清单回来索引的UID排序。

但它需要排序ids阵列。

有没有一种简单的方法来做到这一点与mongoid?谢谢。

+0

的可能的复制https://stackoverflow.com/questions/7533104/mongoid-find-through-array-of-ids – MrYoshiji

回答

1

使用User.where(:uid.in => ids).order_by(uid: :asc)

或者使用聚合时序列重要

ids = [1, 2, 3] 
match = { "$match" => {"uid" => {"$in" => ids } } } 
field = { "$addFields" => { "__order" => { "$indexOfArray" => [ ids, "$uid" } } } 
sort = { "$sort" : { "__order" : 1 } }; 
User.collection.aggregate([match, field, sort]); 
+0

但我想通过不是由uid的ID数组的顺序。这就是问题的全部。 – Calmon

+0

我编辑了一个解决方案,但我需要检查 – gururuby

+0

谢谢,有没有办法保留结果对象类型,因为我想使用.only .skip .limit等等,而且我不能用Mongo ::收藏::查看::聚合 – Calmon