第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定

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

標(biāo)簽:
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')

使用索引的优缺点

优点

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

图片描述

點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機(jī)會得

100積分直接送

付費專欄免費學(xué)

大額優(yōu)惠券免費領(lǐng)

立即參與 放棄機(jī)會
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消