arrays - 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: '' })
我得到那个错误
谁能帮我解决这个问题?我需要路径、价格和类型是唯一的,但我只需要路径作为数组是唯一的,而不是在数组的任何元素中是唯一的
谢谢
解决方案
在 MongoDB 中,索引数组称为多键索引。在这种情况下,MongoDB 分别索引数组的每个值。这就是您获得重复密钥的原因。
一种解决方法是将数组“隐藏”在子文档中,以防止对数组进行实际索引。
例如:
{
"path": {
"sub_doc" : [ "Bla", "Things" ]
}
}
请注意,在这种情况下,数组的元素不再被索引。这意味着您将无法直接在索引上"Bla"
或"Things"
通过索引请求。只有完整的对象sub_doc
。
推荐阅读
- php - 联系表格不发送消息
- elasticsearch - 弹性搜索类型文本不给出匹配查询的结果
- c++ - 如何使用向量求均值和标准差
- php - Laravel 命名空间和文件路径不匹配
- angular - Guard 在尝试重定向到另一个页面时抛出错误
- javascript - 无法在博览会上调试/测试我的 react-native 应用程序
- java - 如何从 mysql 数据库中读取数据并将其插入到已实现的 Hashtable 中?
- php - 如何preg_split所有字符,但不要拆分和
- excel - 为什么 Excel 在剪切并粘贴到新工作表期间不一致地管理剪切行范围?
- rust - 使用闭包从 Option<&T> 获取原始指针是否安全?