前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MongoDB 的索引有哪些 nestjs mongoose示例

MongoDB 的索引有哪些 nestjs mongoose示例

原创
作者头像
Jacky-易小天
修改2024-03-26 10:07:31
760
修改2024-03-26 10:07:31
举报
文章被收录于专栏:mongodbmongodb

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • MongoDB 的索引有哪些 nestjs mongoose示例
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档