如何获取计数最高的 n 个数据集,但返回按名称排序的数据集?
我尝试了以下方法,但不起作用。
db.Foo
.find()
.sort({'count': -1})
.limit(n)
.sort({'name': 1}) // does not work
.exec(...);
除了手动对返回的json数组进行排序之外,还有其他解决办法吗?
比如 SQL 中的子查询?
SELECT *
FROM
( SELECT *
FROM Foo
ORDER BY count DESC
LIMIT n
) AS tmp
ORDER BY name ASC ;
最佳答案
每当查询有多个这样的步骤时,就会出现 aggregate
管道通常是您所需要的:
db.Foo.aggregate([
// Sort all the doc on count, descending
{$sort: {count: -1}},
// Take the first n of those
{$limit: n},
// Resort those n docs on name
{$sort: {name: 1}}
]).exec(...);
关于node.js - Mongoose 首先按一个属性排序和限制,然后按另一个属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35115131/