【问题标题】:sort query result based on array index根据数组索引对查询结果进行排序
【发布时间】:2016-03-17 06:24:28
【问题描述】:

我有来自anotherCollection.. 的 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 中没有rank 字段

非常感谢...

【问题讨论】:

  • 你不能这样做是 Mongodb 查询。从 DB 获得结果后,您需要手动执行此操作。
  • 您能解释一下您希望它们如何排序吗?

标签: javascript arrays mongodb sorting underscore.js


【解决方案1】:

您可以使用给定数组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>');

【讨论】:

  • 你好@NinaScholz 非常感谢你,这个工作......但我不明白这个idSortByRank.indexOf(a._id) - idSortByRank.indexOf(b._id);.. 想详细说明一下,??或者也许是我进一步学习的参考..再次感谢..!!
  • 请看here。如果值较小,则排序函数返回小于 0 的值,如果值相等则返回 0,如果值大于另一个比较值,则返回大于 0 的值。所以最短的是使用 idSortByRank 数组的索引之间的差异。
猜你喜欢
  • 2014-12-02
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多