Arrays E11000使用唯一复合索引中的现有第一个元素插入数组时出现重复键错误

Arrays E11000使用唯一复合索引中的现有第一个元素插入数组时出现重复键错误,arrays,node.js,mongodb,Arrays,Node.js,Mongodb,我有一个集合:test,我有一个唯一的复合索引: db.collection('test').createIndex({path:1,price:1,type:1},{unique:true}) 路径是数组,价格和类型是字符串 我正在尝试插入文档: db.test.insertOne({ path: [ 'Some', 'Thing' ], price: '1.00', type: '' }) 这是可行的,我可以在我的收藏中看到该文档,但当我尝试插入另一个文档时: db.test.insert

我有一个集合:
test
,我有一个唯一的复合索引:
db.collection('test').createIndex({path:1,price:1,type:1},{unique:true})

路径是数组,价格和类型是字符串

我正在尝试插入文档:

db.test.insertOne({ path: [ 'Some', 'Thing' ], price: '1.00', type: '' })
这是可行的,我可以在我的收藏中看到该文档,但当我尝试插入另一个文档时:

db.test.insertOne({ path: [ 'Some', 'Thing', 'Else' ], price: '1.00', type: '' })
我得到这个错误:

2019-08-20T11:04:10.560+0300 E QUERY    [js] WriteError: E11000 duplicate key error collection: api.test index: path_1_price_1_type_1 dup key: { : "Some", : "1.00", : "" } :
WriteError({
        "index" : 0,
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: api.test index: path_1_price_1_type_1 dup key: { : \"Some\", : \"1.00\", : \"\" }",
        "op" : {
                "_id" : ObjectId("5d5ba97a19d534f6cc2fc050"),
                "path" : [
                        "Some",
                        "Thing"
                ],
                "price" : "1.00",
                "type" : ""
        }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
我曾尝试将updateOne与upsert:true一起使用,但我得到了相同的错误 即使第一个字段值是一个数组,当我尝试插入数组并给我
dup键:{:“Some”、:“1.00”、:“}
时,它似乎只显示第一个元素的红色

以下是我在控制台中运行的完整代码:

db.collection('test').createIndex({ path: 1, price: 1, type: 1 }, { unique: true });
db.test.insertOne({ path: [ 'Some', 'Thing' ], price: '1.00', type: '' })
db.test.insertOne({ path: [ 'Some', 'Thing', 'Else' ], price: '1.00', type: '' })
路径可能不同,因此如果我尝试插入以下内容:

db.test.insertOne({ path: [ 'Some', 'Thing' ], price: '1.00', type: '' })
db.test.insertOne({ path: [ 'Bla', 'Bla' ], price: '1.00', type: '' })
它起作用了

但如果其中一个数组元素存在:

db.test.insertOne({ path: [ 'Bla', 'Thing' ], price: '1.00', type: '' })
我知道那个错误

有人能帮我解决这个问题吗?我需要路径、价格和类型是唯一的,但我只需要路径作为一个数组是唯一的,而不是作为数组中的任何元素是唯一的


感谢MongoDB,索引数组被称为多键索引。在本例中,MongoDB分别为数组的每个值编制索引。这就是为什么你会得到你的复制钥匙

解决方法是在子文档中“隐藏”数组,以防止对数组进行实际索引

例如:

{
  "path": {
     "sub_doc" : [ "Bla", "Things" ]
  }
}

注意,在这种情况下,数组的元素不再被索引。这意味着您将无法通过索引直接请求
“Bla”
“Things”
。只有完整对象
sub_doc

,以确保我可以使用唯一的复合索引
db.test.createIndex({path.sub_doc:1,price:1,type:1},{Unique:true})?不,不,如果你这样做,你会得到完全相同的问题。您必须执行
db.test.createIndex({path:1,price:1,type:1},{unique:true})。在这种情况下,MongoDB将索引
路径
作为一个整体,而不查看子数组。