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

MongoDB:如何在保存数据时创建索引以优化查询效率

如何在Mongoose中创建索引实现高效查询

要让查询{type: "Individual"}的totalDocsExamined仅为2,你需要给type字段创建单字段索引,让MongoDB直接定位到匹配的文档,避免全集合扫描。

方法1:在Schema定义时指定索引(推荐)

在定义Customer模型的Schema时,直接给type字段添加索引配置,集合初始化时会自动创建索引:

const mongoose = require('mongoose');

const customerSchema = new mongoose.Schema({
  name: String,
  type: {
    type: String,
    index: true // 为type字段创建单字段升序索引
  },
  country: String
});

const Customer = mongoose.model('Customer', customerSchema);

方法2:保存数据后动态创建索引

如果Schema已经定义完成,可在数据保存后通过集合对象创建索引:

const customer = new Customer({ "name": "Mr A","type": "Individual","country": "Nepal"});
await customer.save()
const customer2 = new Customer({ "name": "Mr B","type": "Individual","country": "Singapore"});
await customer2.save()
const customer3 = new Customer({ "name": "Company C","type": "Corporate","country": "Singapore"});
await customer3.save()

// 创建type字段的单字段索引
await Customer.collection.createIndex({ type: 1 });

注:1表示升序索引,-1表示降序,对于精确匹配的查询,两种顺序的性能无差异。

验证效果

执行你的查询语句后,查看executionStats.totalDocsExamined:

const findCustomer = await Customer.find({type: "Individual"}).explain("executionStats");
console.log(findCustomer.executionStats.totalDocsExamined); // 输出2

若首次创建索引后立即查询仍显示3,可等待索引构建完成后再试,或通过await Customer.collection.indexes()确认索引已成功创建。

内容的提问来源于stack exchange,提问作者Alan Tang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:07:49