您是正确的,唯一索引的限制正如您所描述的那样。但是,这仅适用于奇异值字段。一旦在数组上使用唯一索引,它就会成为唯一+多键索引。
基本上,当您在数组字段上创建索引时,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 }
这就是为什么您不能在索引中索引多个数组字段的原因。如果您有多个数组,则索引条目的数量将是两个数组长度的乘积。您的索引可能很容易大于您的数据,并且扫描如此大的索引可能需要相当长的时间。