如何按多个字段在猫鼬中排序?

时间:2021-02-05 00:38:36

标签: javascript mongodb mongoose

假设我有这个架构,它有两个字段

someDate: Date
isPriority: boolean

并且我想通过 someDate 记录进行排序查询,isPriority: true 应该始终排在第一位。 那么它应该是什么样子的呢?现在我知道如何像这样按日期排序:

Record.find().sort({ someDate: -1 });

1 个答案:

答案 0 :(得分:0)

我认为在某个时候 MongoDB 开始支持排序(通过它使用的索引以外的方式),并且键顺序可以支持排序。

根据 MongoDB documentation,要实现“稳定”排序,请确保您有一个唯一的列作为最后一个键。

db.restaurants.find().sort( { "borough": 1, "_id": 1 } )

因此,对于您的特定查询,请使用:

{isPriority: 1, someDate: -1, _id: 1}.

错误的方式,意思是

{someDate: -1, isPriority: 1, _id: 1}