根据数组索引对查询结果进行排序

sort query result based on array index

我有来自anotherCollection的id数组..在我做了很多计算之后,我得到:

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

我需要通过 idSortByRank 从 mongodb 的 MyCollection sorted/indexed 集合中 return 对象,如下所示:

//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

中没有 rank 字段

非常感谢...

您可以使用给定数组的索引进行排序 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>');