索引的概念
-
在数据库中,索引类似于一个目录,用于快速定位到具体的内容,使用索引可以显著的提高查询效率,但会增加额外的存储空间
-
无索引的查询:
-
带索引的查询:
mongodb 中的索引操作
在 mongodb 中,索引的存储结构是 B- 树
创建索引
-
为某个集合创建索引
db.<collection>.createIndex(keys, [options]);
-
keys:指定索引中关联的字段,以及字段的排序方式,1 为升序,-1 为降序;
// 索引关联 age 字段,按照升序排序 { age: 1 }
-
options 索引的配置
- background:默认 false ,建索引过程会阻塞其它数据库操作,是否以后台的形式创建索引
- unique:默认 false ,是否是唯一索引
- name:索引名称
其他索引操作
方法 | 描述 |
---|---|
db.collection.getIndexes() | 查看所有索引 |
db.collection.totalIndexSize() | 查看集合索引占用空间 |
db.collection.dropIndexes() | 删除所有索引 |
db.collection.dropIndex(“索引名称”) | 删除集合指定索引 |
mongoose 案例
由于使用 mongoose 来操作索引比较简单,这里使用 mongoose 来对比使用索引前后的性能
-
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 条数据
-
执行 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();
-
models/User.js 增加索引
age: { type: Number, default: 18, index: true, // 新增索引 },
-
执行 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();
最佳实践
针对数据量大的集合使用索引
针对常用的查询或排序字段使用索引
尽量避免在程序运行过程中频繁创建和删除索引
MongoDB👉 删除文档
上一篇