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 });
相关推荐
程序猿零零漆3 分钟前
【金仓数据库征文】金仓数据库:国产化浪潮下的技术突破与行业实践
数据库·金仓数据库 2025 征文·数据库平替用金仓
王佑辉6 分钟前
【mongodb】系统保留的数据库名
mongodb
浩浩测试一下14 分钟前
SQL注入高级绕过手法汇总 重点
数据库·sql·安全·web安全·网络安全·oracle·安全架构
Pasregret38 分钟前
缓存与数据库一致性深度解析与解决方案
数据库·缓存·wpf
skywalk816341 分钟前
Graph Database Self-Managed Neo4j 知识图谱存储实践2:通过官方新手例子入门(未完成)
数据库·知识图谱·neo4j
Lucky GGBond44 分钟前
MySQL 报错解析:SQLSyntaxErrorException caused by extra comma before FROM
数据库·mysql
Claudio1 小时前
【MySQL】联合索引和覆盖索引(索引失效的误区讲解+案例分析)
数据库
纪元A梦1 小时前
Redis最佳实践——性能优化技巧之监控与告警详解
数据库·redis·性能优化
GarfieldFine2 小时前
MySQL索引使用一定有效吗?如何排查索引效果?
数据库·mysql
cypking2 小时前
mysql 安装
数据库·mysql·adb