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 });
相关推荐
xixixi777778 分钟前
了解一下APM工具——就像给软件系统装的“全身CT”,能实时透视从用户点击到后端数据库的每个环节性能,精准定位哪里慢、为什么慢
数据库·安全·数据采集·apm·日志监控
q***99424 分钟前
PON架构(全光网络)
网络·数据库·架构
Leon-Ning Liu28 分钟前
Oracle查看正在rebuild online的索引
数据库·oracle
bhots￿28 分钟前
oracle 物化视图设置自动更新日志
数据库·oracle
苦学编程的谢1 小时前
Redis_12_持久化(1)
数据库·redis·缓存
百***46801 小时前
MySQL的底层原理与架构
数据库·mysql·架构
百***12221 小时前
Redis开启远程访问
数据库·redis·缓存
czhc11400756631 小时前
Java1112 基类 c#vscode使用 程序结构
android·java·数据库
倔强的石头_1 小时前
openGauss实战:Python开发与AI向量数据库应用
数据库
马克学长2 小时前
SSM快递代收系统00pay(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库