MongoDB 的索引有哪些 nestjs mongoose示例

MongoDB 的索引有哪些 nestjs mongoose示例

复合索引(Compound Index): 索引多个字段,允许对这些字段的组合进行高效查询。例如,您可以创建一个索引 { name: 1, age: 1 },以便可以快速查询按姓名和年龄排序的结果。

typescript 复制代码
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

userSchema.index({ name: 1, age: 1 });

哈希索引(Hashed Index): 用于哈希键,例如 ObjectId。这可以提高对哈希键的查询性能,因为 MongoDB 不需要扫描整个集合来查找匹配的文档。

typescript 复制代码
const userSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId
});

userSchema.index({ _id: 'hashed' });

地理空间索引(Geospatial Index): 用于地理空间数据,例如点、线和多边形。这允许基于地理位置进行高效的范围查询和最近邻搜索。

typescript 复制代码
const locationSchema = new mongoose.Schema({
  type: {
    type: String,
    enum: ['Point']
  },
  coordinates: [Number]
});

const placeSchema = new mongoose.Schema({
  location: locationSchema
});

placeSchema.index({ location: '2dsphere' });

全文本索引(Full-Text Index): 用于文本数据,例如字符串和文本字段。这允许对文本内容进行快速全文搜索。

typescript 复制代码
const articleSchema = new mongoose.Schema({
  title: String,
  content: String
});

articleSchema.index({ title: 'text', content: 'text' });

唯一索引(Unique Index): 确保集合中每个文档的索引字段值都是唯一的。这对于防止重复数据和维护数据完整性非常有用。

typescript 复制代码
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  }
});

稀疏索引(Sparse Index): 仅为具有索引字段非空值的文档创建索引条目。这可以节省存储空间,并可以提高某些查询的性能。

typescript 复制代码
const userSchema = new mongoose.Schema({
  preferences: {
    type: Object,
    sparse: true
  }
});

覆盖索引(Covering Index): 包含查询中所需的所有字段,从而避免额外的磁盘访问来检索数据。这可以显着提高查询性能。

typescript 复制代码
const orderSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  product: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product'
  },
  quantity: Number
});

orderSchema.index({ user: 1, product: 1, quantity: 1 }, { unique: true });
相关推荐
ldmd28417 分钟前
Go语言实战:入门篇-4:与数据库、redis、消息队列、API
数据库·redis·缓存
是Dream呀23 分钟前
工业级时序数据库选型指南:技术架构与场景化实践
数据库·架构·时序数据库
骑士99911129 分钟前
时序数据库TDengine用法
数据库·时序数据库·tdengine
Pluchon30 分钟前
硅基计划5.0 MySQL 叁 E-R关系图&联合/多表查询&三大连接&子查询&合并查询
开发语言·数据库·学习·mysql
Gold Steps.32 分钟前
MySQL 8+ 日志管理与数据备份恢复实战指南
数据库·mysql·数据安全
程序员鱼皮35 分钟前
老弟第一次学 Redis,被坑惨了!小白可懂的保姆级 Redis 教程
数据库·redis·程序员
oak隔壁找我1 小时前
Druid 数据库连接池源码详细解析
java·数据库·后端
不剪发的Tony老师1 小时前
Yearning:一个免费开源的SQL审核平台
数据库·sql·mysql
Gauss松鼠会2 小时前
GaussDB慢sql信息收集和执行计划查看
数据库·sql·gaussdb