首页 > 解决方案 > E11000 在唯一复合索引中插入具有现有第一个元素的数组时出现重复键错误

问题描述

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

path 是一个数组,price 和 type 是字符串

我正在尝试插入文档:

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 key: { : "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: '' })

我得到那个错误

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

谢谢

标签: arraysnode.jsmongodb

解决方案


在 MongoDB 中,索引数组称为多键索引。在这种情况下,MongoDB 分别索引数组的每个值。这就是您获得重复密钥的原因。

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

例如:

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

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


推荐阅读