MongoDB 的索引有哪些 nestjs mongoose示例

MongoDB 的索引有哪些 nestjs mongoose示例

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

const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

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

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

const userSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId
});

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

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

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): 用于文本数据,例如字符串和文本字段。这允许对文本内容进行快速全文搜索。

const articleSchema = new mongoose.Schema({
  title: String,
  content: String
});

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

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

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  }
});

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

const userSchema = new mongoose.Schema({
  preferences: {
    type: Object,
    sparse: true
  }
});

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

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 });

相关推荐

  1. MongoDB 索引哪些 nestjs mongoose示例

    2024-03-26 14:36:06       16 阅读
  2. MongoDB】--MongoDB组合索引

    2024-03-26 14:36:06       12 阅读
  3. 什么是索引索引哪些优缺点?

    2024-03-26 14:36:06       13 阅读
  4. MySQL索引哪些优缺点

    2024-03-26 14:36:06       34 阅读
  5. MongoDB 索引

    2024-03-26 14:36:06       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-26 14:36:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-26 14:36:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-26 14:36:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-26 14:36:06       18 阅读

热门阅读

  1. 在线数据格式工具

    2024-03-26 14:36:06       14 阅读
  2. 论文阅读--Offline RL Without Off-Policy Evaluation

    2024-03-26 14:36:06       14 阅读
  3. vue/js总结合集

    2024-03-26 14:36:06       16 阅读
  4. 面试算法-117-组合总和 III

    2024-03-26 14:36:06       13 阅读
  5. 缓存Caffine

    2024-03-26 14:36:06       19 阅读
  6. django关于文件分块上传的简单实现(template+view)

    2024-03-26 14:36:06       18 阅读
  7. Promise封装ajax

    2024-03-26 14:36:06       16 阅读
  8. 【力扣】零钱兑换和零钱兑换2,动态规划算法

    2024-03-26 14:36:06       17 阅读
  9. Kafka简介

    2024-03-26 14:36:06       17 阅读