【金秋打卡】第4天 mongodb 索引
2022/10/29 4:24:59
本文主要是介绍【金秋打卡】第4天 mongodb 索引,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
课程名称: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')
使用索引的优缺点
优点
- 大幅度提高查询效率
缺点 - 索引会增加写操作的代价
这篇关于【金秋打卡】第4天 mongodb 索引的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb
- 2024-03-14clickhouse-go