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 });
相关推荐
8Qi818 分钟前
Redis哨兵模式(Sentinel)深度解析
java·数据库·redis·分布式·缓存·sentinel
数据库小组22 分钟前
从业务库到实时分析库,NineData 构建 MySQL 到 SelectDB 同步链路
数据库·mysql·数据库管理工具·数据同步·ninedata·数据库迁移·selectdb
CDN36028 分钟前
CDN HTTPS 证书配置失败?SSL 部署与域名绑定常见问题
数据库·https·ssl
Chengbei1134 分钟前
一次比较简单的360加固APP脱壳渗透
网络·数据库·web安全·网络安全·系统安全·网络攻击模型·安全架构
寒秋花开曾相惜35 分钟前
(学习笔记)3.9 异质的数据结构(3.9.1 结构)
c语言·网络·数据结构·数据库·笔记·学习
mcooiedo1 小时前
mybatisPlus打印sql配置
数据库·sql
wudl55661 小时前
MySQL 8.0.42 Docker 开发部署手册
数据库·mysql·docker
xhuiting1 小时前
MySQL专题总结(四)—— 高可用
java·数据库·mysql
kjmkq1 小时前
目工业级宽温SSD哪个品牌不掉盘最稳定?宽温环境下的稳定性性技术解析
数据库·存储
Predestination王瀞潞1 小时前
Java EE3-我独自整合(第二章:Spring IoC 入门案例)
数据库·spring·java-ee