第十章 多值索引

本文详细介绍了MongoDB中的多值索引,包括如何创建、唯一性约束、限制、排序、分片键以及在查询中的应用。多值索引允许在数组字段上创建索引,提高查询效率,但也有其限制,如不能作为分片键,且在某些查询场景下可能影响性能。
摘要由CSDN通过智能技术生成

第十章 多值索引

  • 创建多值索引
  • 索引范围
  • 唯一多值索引
  • 多值索引限制

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.

在一个类型为数组的字段上建立索引,MonogoDB会为每一个数组元素映射对应索引项,以提高对数组类型查询的效率。多值索引是构建在数组上,数组元素可以是基本类型,也可以是文档类型。

创建多值索引

To create a multikey index, use the db.collection.createIndex() method:

创建多值索引,使用到了 db.collection.createIndex() 方法。

db.collection_name.createIndex({
    <field>: < 1 or -1> })

MongoDB automatically creates a multikey index if any indexed field is an array; you do not need to explicitly specify the multikey type.

MongoDB 会自动地为数组类型的字段创建多值索引;你不需要显示创建多值索引。

唯一多值索引

For unique indexes, the unique constraint applies across separate documents in the collection rather than within a single document.

对于唯一索引来说,它的作用可以在集合中区分各个文档。

Because the unique constraint applies to separate documents, for a unique multikey index, a document may have array elements that result in repeating index key values as long as the index key values for that document do not duplicate those of another document.

因为唯一索引可以限制区分文档,对于唯一多值索引也类似,只要文档的数组字段的元素不于其他文档数组字段的元素不重复即可。

假如,这有 fruit 的集合,有 nameprices 字段:

{
   
    "_id": ObjectId("6018bded893400009b0000f4"),
    "name": "apple",
    "prices": [ 5, 10]
}

prices 上建立唯一多值索引:

db.fruit.createIndex({
   prices
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值