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 });
相关推荐
Java面试题总结几秒前
PostgreSQL 性能调优:内存、I/O 与连接管理
数据库·postgresql
北秋,3 分钟前
Oracle 数据库基础用法
数据库·oracle
CLX05054 分钟前
C#怎么实现全局异常过滤器_C#如何捕获控制器报错【核心】
jvm·数据库·python
多加点辣也没关系12 分钟前
设计模式-享元模式
数据库·设计模式·享元模式
牢七18 分钟前
Mailvelope
数据库
阿里云瑶池数据库25 分钟前
如何破解多租户隔离与性能难题?PolarDB PostgreSQL实战指南
数据库·postgresql
倔强的石头_35 分钟前
异构操作系统架构下的数据库表空间高级管理:路径兼容与自动化运维实战
数据库
倒霉熊dd1 小时前
Python 学习(第二部分:函数、模块与面向对象编程)
前端·数据库·python
无盐海1 小时前
Foundatio,内存,Redis 缓存
数据库·redis·缓存
六月雨滴1 小时前
Oracle 数据库内存管理
数据库·oracle