Javascript 基于数组索引对查询结果进行排序

Javascript 基于数组索引对查询结果进行排序,javascript,arrays,mongodb,sorting,underscore.js,Javascript,Arrays,Mongodb,Sorting,Underscore.js,我有另一个集合中的id数组。。经过多次计算,我得到: idSortByRank = ["cxwMoC3k6kpf4mr5o","HFYjC5nuT9hKhdyFC","GiM7NCLjck6Pet8Wm"] 我需要从MyCollection的mongodb集合返回对象,该集合由idSortByRank排序/索引,如下所示: //expected result should index/sort the same as idSortByRank [ {"_id": "cxwMoC3k6kpf4

我有另一个集合中的id数组。。经过多次计算,我得到:

idSortByRank = ["cxwMoC3k6kpf4mr5o","HFYjC5nuT9hKhdyFC","GiM7NCLjck6Pet8Wm"]
我需要从MyCollection的mongodb集合返回对象,该集合由idSortByRank排序/索引,如下所示:

//expected result should index/sort the same as idSortByRank

[
{"_id": "cxwMoC3k6kpf4mr5o", other field},
{"_id": "HFYjC5nuT9hKhdyFC", other field},
{"_id": "GiM7NCLjck6Pet8Wm", other field}
]
我这样做了,但没有按预期排序:

MyCollection.find({_id:{$in:idSortByRank}});
我在
MyCollection


非常感谢…

您可以使用给定数组的索引进行排序
idSortByRank

var idSortByRank=[“cxwMoC3k6kpf4mr5o”、“HFYjC5nuT9hKhdyFC”、“GiM7NCLjck6Pet8Wm”],
数据=[{u id:“GiM7NCLjck6Pet8Wm”},{u id:“HFYjC5nuT9hKhdyFC”},{u id:“cxwMoC3k6kpf4mr5o”}];
数据排序(函数(a,b){
返回idSortByRank.indexOf(a._id)-idSortByRank.indexOf(b._id);
});

document.write(''+JSON.stringify(数据,0,4)+'')您不能这样做,这是Mongodb查询。在从DB获得结果后,您需要手动执行此操作。您能解释一下您希望如何对它们进行排序吗?您好@NinaScholz,非常感谢您,,,这可以工作…但我不理解此
idSortByRank.indexOf(a.\u id)-idSortByRank.indexOf(b.\u id)。。想详细说明一下吗,,??或者是我进一步学习的参考资料。再次感谢。。!!请看一看。如果值较小,则sort函数返回小于0的值;如果值相等,则返回0;如果值大于另一个比较值,则返回大于0的值。因此,最短的方法是使用
idSortByRank
数组的索引之间的差值eb。