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
相关产品推荐
相关产品推荐

