第十章 多值索引
- 创建多值索引
- 索引范围
- 唯一多值索引
- 多值索引限制
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
的集合,有 name
和 prices
字段:
{
"_id": ObjectId("6018bded893400009b0000f4"),
"name": "apple",
"prices": [ 5, 10]
}
在 prices
上建立唯一多值索引:
db.fruit.createIndex({
prices