我从anotherCollection获得ID数组。.经过多次计算,我得到了:

idSortByRank = ["cxwMoC3k6kpf4mr5o","HFYjC5nuT9hKhdyFC","GiM7NCLjck6Pet8Wm"]


我需要从idSortByRank排序/索引的MyCollection的mongodb集合中返回对象,如下所示:

//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}});


我在rank中没有MyCollection字段

非常感谢...

最佳答案

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



var idSortByRank = ["cxwMoC3k6kpf4mr5o", "HFYjC5nuT9hKhdyFC", "GiM7NCLjck6Pet8Wm"],
    data = [{ "_id": "GiM7NCLjck6Pet8Wm" }, { "_id": "HFYjC5nuT9hKhdyFC" }, { "_id": "cxwMoC3k6kpf4mr5o" }];

data.sort(function (a, b) {
    return idSortByRank.indexOf(a._id) - idSortByRank.indexOf(b._id);
});
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

10-06 12:04