为了账号安全,请及时绑定邮箱和手机立即绑定

【金秋打卡】第4天 mongodb 索引

标签:
MongoDB Node.js

课程名称web前端架构师

课程章节:第14周 第七章 mongodb 高级内容

主讲老师:张轩

课程内容: mongodb 索引

mongodb 索引

索引(Index),为了提高查询效率
MongoDB 的文件类型:BSON, Binary JSON,主要被用作MongoDB数据库中的数据存储和网络传输格式。

假如没有索引,必须扫描这个巨大BSON对象集合中的每个文档并选取那些符合查询条件的记录,这样是低效的。

索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中。

下面写代码进行测试

先写入50000条数据

import { connect } from './index'
import mongoose, { Schema } from 'mongoose'
const UserSchema = new Schema({
  username: String,
  password: {
    type: String,
    select: false
  },
  hobbies: [String],
  date: Date,
  createAt: Date,
  age: Number
})

UserSchema.pre('save', function (next) {
  this.createAt = new Date()
  next()
})

export const User = mongoose.model('TestUser', UserSchema);
async function start() {
  await connect()
  const arr = []
  for (let i = 0; i < 50000; i++) {
    arr.push({
      username: 'aaa' + i,
      password: '123456',
      hobbies: ['play', 'sleep'],
      date: new Date(),
      age: 20
    })
  }
  await User.insertMany(arr)
}

然后查询并输出查询信息

const user = await User.find({ username: 'aaa49999' }).explain()
console.log(user)

输出的查询信息

{
...
executionStats: {
    executionSuccess: true,
    nReturned: 1,
    executionTimeMillis: 27,
    totalKeysExamined: 0,
    totalDocsExamined: 50000,
    ...
}

其中 executionTimeMillis 时耗时, totalDocsExamined 时遍历了多少文档,这里遍历了 50000 次

通过索引查询

const user = await User.find({ _id: '635a9984821264c6b2645f08' }).explain()
console.log(user)

输出查询信息,可以看到耗时为0, 遍历了 1 次,可以看到使用索引查询效率非常高

{
executionStats: {
  ...
  executionSuccess: true,
  nReturned: 1,
  executionTimeMillis: 0,
  totalKeysExamined: 1,
  totalDocsExamined: 1,
  ...
  }
  ...
}

索引的管理

创建索引

将 username 设置为索引

const UserSchema = new Schema({
  //   author: ObjectId,
  username: {
    type: String,
    unique: true
  },
  password: {
    type: String,
    select: false
  },
  hobbies: [String],
  date: Date,
  createAt: Date,
  age: Number
})

查看所有索引

const res = await User.listIndexes()
console.log(res)

输出

[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { username: 1 }, name: 'username_1' }
]

然后在使用 查询

const user = await User.find({ username: 'aaa49999' }).explain()
console.log(user)

我们会发现查询效率变高了,因为 username 变成了索引

删除索引

原始 mongodb 命令删除索引

db.testusers.dropIndex('username_1')

使用索引的优缺点

优点

  • 大幅度提高查询效率
    缺点
  • 索引会增加写操作的代价

图片描述

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Python工程师
手记
粉丝
2
获赞与收藏
1

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消