索引的概念

  1. 在数据库中,索引类似于一个目录,用于快速定位到具体的内容,使用索引可以显著的提高查询效率,但会增加额外的存储空间

  2. 无索引的查询:

  3. 带索引的查询:

mongodb 中的索引操作

mongodb 中,索引的存储结构是 B-

创建索引

  1. 为某个集合创建索引

    db.<collection>.createIndex(keys, [options]);
    
  2. keys:指定索引中关联的字段,以及字段的排序方式,1 为升序,-1 为降序;

    // 索引关联 age 字段,按照升序排序
    { age: 1 }
    
  3. options 索引的配置

    • background:默认 false ,建索引过程会阻塞其它数据库操作,是否以后台的形式创建索引
    • unique:默认 false ,是否是唯一索引
    • name:索引名称

其他索引操作

方法 描述
db.collection.getIndexes() 查看所有索引
db.collection.totalIndexSize() 查看集合索引占用空间
db.collection.dropIndexes() 删除所有索引
db.collection.dropIndex(“索引名称”) 删除集合指定索引

mongoose 案例

由于使用 mongoose 来操作索引比较简单,这里使用 mongoose 来对比使用索引前后的性能

  1. addTestUsers.js

    const { User } = require("./models");
    
    function random(min, max) {
      return Math.floor(Math.random() * (max - min)) + min;
    }
    
    async function add() {
      var users = [];
      for (var i = 0; i < 100000; i++) {
        users.push({
          loginId: "user_" + i,
          loginPwd: "4297f44b13955235245b2497399d7a93",
          age: random(10, 50),
          name: "test",
          address: {
            province: "黑龙江",
            city: "哈尔滨",
          },
        });
      }
      console.log("构造数据完成");
      await User.insertMany(users);
      console.log("添加数据完成");
    }
    
    add(); // 新增 10W 条数据
    
  2. 执行 index.js,没增加索引

    var { User, Operation } = require("./models");
    
    async function test() {
      console.time();
      const number = await User.countDocuments({
        age: {
          $gt: 25,
          $lt: 30,
        },
      });
      console.timeEnd(); // 93.276ms
      console.log(number);
    }
    test();
    
  3. models/User.js 增加索引

    age: {
      type: Number,
      default: 18,
      index: true, // 新增索引
    },
    
  4. 执行 index.js,没增加索引

    var { User, Operation } = require("./models");
    
    async function test() {
      console.time();
      const number = await User.countDocuments({
        age: {
          $gt: 25,
          $lt: 30,
        },
      });
      console.timeEnd(); // 24.2ms
      console.log(number);
    }
    test();
    

最佳实践

  1. 针对数据量大的集合使用索引

  2. 针对常用的查询或排序字段使用索引

  3. 尽量避免在程序运行过程中频繁创建和删除索引

打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 索引的概念
  2. 2. mongodb 中的索引操作
    1. 2.1. 创建索引
    2. 2.2. 其他索引操作
  3. 3. mongoose 案例
  4. 4. 最佳实践