MongoDB 使用唯一索引覆盖或跳过现有文档

问题描述 投票:0回答:1

我有一个带有 Spring Data 的 Spring Boot 应用程序。另外,我在 MongoDB 中有一个集合。该集合包含一些字段,我通过 3 个字段创建了一个带有 UNIQUE 标志的索引,例如:姓名 + 姓氏 + 年龄。

当我插入具有以下 Java 格式

repository.saveAll(list)
的文档时,我的集合已经包含了这些文档的一部分 - Mongo 在我的脸上抛出一个异常,如:

服务器本地主机上的批量写入操作错误。写入错误:[BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: myCollection.name index: name_1_surname_1_age_1 dup key

这是预期的行为,但我需要使用以下逻辑配置 Mongo:

  • 当插入多个文档时,索引显示“集合中已存在一些文档”——忽略这些文档,或跳过它们,或直接覆盖,无任何例外。

这可能吗?同时处理多个文档对我来说很重要。

你知道怎么做吗?作为更好的结果,我想在没有自定义查询的情况下使用一些属性或附加标志。 谢谢。

java spring mongodb spring-data-jpa database-indexes
1个回答
0
投票

在我的例子中,我有一个唯一索引,我正在尝试将文档更新为:插入新文档,并跳过现有文档。

文档缺少这个或者没有明确说明,但是你需要设置

ordered: false
。在这种情况下,它将继续操作并在最后返回异常列表。

MyModel.collection.bulk_write(
  [
    { update_one: { filter: {...}, update: { '$set' => {...}, upsert: true } },
    { update_one: { filter: {...}, update: { '$set' => {...}, upsert: true } },
    { update_one: { filter: {...}, update: { '$set' => {...}, upsert: true } },
    ...
  ],
  ordered: false
)

最后你会得到这样的错误:

Multiple errors:
[11000]: E11000 duplicate key error collection: my_database.my_collection index: my_unique_index dup key: { ... };
[11000]: E11000 duplicate key error collection: my_database.my_collection index: my_unique_index dup key: { ... };
(Mongo::Error::BulkWriteError)

我不得不稍微格式化一下输出,否则它会变成一条长线。我的示例也是用 Ruby 编写的,但它应该在任何地方都是一样的。

我不确定这是期望的行为还是副作用,但它确实有效。

© www.soinside.com 2019 - 2024. All rights reserved.