3

我正在尝试使用复合索引创建 mongo 文档。我的示例文档看起来像这样

{ fname:“fname1”,lname:“lname1”,任务:[“t11”,“t12”,“t13”]}

{ fname:“fname2”,lname:“lname2”,任务:[“t21”,“t22”,“t23”]}

{ fname:“fname3”,lname:“lname3”,任务:[“t31”,“t32”,“t33”]}

索引如下

createIndex({ fname: 1, lname: 1, task: 1 }, { unique: true, name: 'some-index-name'})

我期待的是

如果有任何变化

  • fname
  • 名字
  • 任务(任何部分数据更改 - 至少一个元素)

应被视为独特的文件。

我收到此异常“ E11000 重复密钥错误集合

我查看了闲置的链接。但无法弄清楚。

部分索引有什么限制?

https://docs.mongodb.com/manual/core/index-partial/

https://docs.mongodb.com/manual/indexes/#create-an-index

Mongo代码库: https ://github.com/mongodb/mongo/blob/69dec2fe8fed6d32ec4998ea7ec7ab063cb5b788/src/mongo/db/catalog/index_catalog.cpp#L422

4

1 回答 1

6

您是正确的,唯一索引的限制正如您所描述的那样。但是,这仅适用于奇异值字段。一旦在数组上使用唯一索引,它就会成为唯一+多键索引。

基本上,当您在数组字段上创建索引时,MongoDB 会为该文档中的每个数组字段创建一个索引条目。这称为多键索引。

例如,文档:

{a:1, b:[1, 2, 3]}

与索引:

db.test.createIndex({a:1, b:1})

对于 的每个数组元素,索引中将包含三个条目b

{a:1, b:1}
{a:1, b:2}
{a:1, b:3}

a因此,如果您在字段和上创建唯一索引b

db.test.createIndex({a:1, b:1}, {unique:true})

所有这些插入都将因违反唯一索引而失败:

> db.test.insert({a:1, b:1})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 1.0 }

> db.test.insert({a:1, b:2})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 2.0 }

> db.test.insert({a:1, b:3})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 3.0 }

> db.test.insert({a:1, b:[1]})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 1.0 }

> db.test.insert({a:1, b:[1,2]})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 1.0 }

> db.test.insert({a:1, b:[1,2,3]})
E11000 duplicate key error collection: test.test index: a_1_b_1 dup key: { : 1.0, : 1.0 }

这就是为什么您不能在索引中索引多个数组字段的原因。如果您有多个数组,则索引条目的数量将是两个数组长度的乘积。您的索引可能很容易大于您的数据,并且扫描如此大的索引可能需要相当长的时间。

于 2018-03-08T01:02:29.137 回答