You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Mongoose创建Schema时如何指定索引字段的排序规则

Mongoose索引排序方向配置方法

你可以通过两种方式指定索引的排序方向:

  • 字段级直接配置
    直接替换index属性的布尔值即可:1代表升序,-1代表降序,修改后的示例代码如下:
const animalSchema = new Schema({
  name: String,
  type: String,
  score: { type: [Number], index: -1 } // 降序索引,需要升序则赋值为1
});
  • Schema级独立配置
    如果需要配置多字段联合索引、或者后续调整索引规则更灵活,也可以调用Schema的index方法单独配置:
const animalSchema = new Schema({
  name: String,
  type: String,
  score: [Number]
});
// 指定score字段为降序索引
animalSchema.index({ score: -1 });

补充说明:你的score字段是数组类型,MongoDB会自动为数组内的每一个元素创建索引,配置的排序方向对数组索引同样生效,查询时对应的排序条件会命中该索引。

内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:45:03