【问题标题】:Not able to update mongo collection using Bulkwrite无法使用 Bulkwrite 更新 mongo 集合
【发布时间】:2021-04-20 10:30:11
【问题描述】:

我有以下字段的 mongo 集合

Sno1 Sno2 位置

集合中的数据格式

Sno1    Sno2   Location
--------------------------------
1000    2000   Hyderabad

我想将位置更新为“Chennai”。当我在 MongoCollection 类上使用 bulkWrite 方法时,它返回以下异常

Here is the snippet

mongoColl.bulkWrite(docs, writeOptions);  --> docs is List<InsertOneModel<Document>> 


BulkWriteError(index=0, code=11000, message='E11000 duplicate key error collection'

在 Sno1 和 Sno2 字段上创建了一个索引。如何更新收藏?我不想删除索引。任何想法将不胜感激

【问题讨论】:

  • 您是否需要使用相同的更新来更新所有文档(例如,将所有文档的位置更改为恒定值)还是每个文档都应该有不同的更新?
  • @geobreze 我必须根据 Sno1 和 Sno2 更新所有具有不同位置的文档

标签: java mongodb mongodb-query


【解决方案1】:

您可以使用com.mongodb.client.model.UpdateOneModel,因此 mongo 将尝试更新现有文档的一个(或多个)字段。

MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("test");

List<UpdateOneModel<Document>> updateList = List.of(
                new UpdateOneModel<>(new Document(Map.of("col1", "val1")), Updates.set("field", "1")),
                new UpdateOneModel<>(new Document(Map.of("col1", "val2")), Updates.set("field", "2")));
BulkWriteOptions options = new BulkWriteOptions().ordered(false);
collection.bulkWrite(updateList, options);

如果您需要 upsert 行为,可以使用 com.mongodb.client.model.ReplaceOneModel 和 ReplaceOptions.upsert(true):

ReplaceOptions replaceOptions = new ReplaceOptions().upsert(true);
List<ReplaceOneModel<Document>> replaceList = List.of(
                new ReplaceOneModel<>(new Document(Map.of("col1", "val3")), new Document(Map.of("col1", "val3", "field", "1")), replaceOptions),
                new ReplaceOneModel<>(new Document(Map.of("col1", "val4")), new Document(Map.of("col1", "val4", "field", "2")), replaceOptions));
collection.bulkWrite(replaceList, options);

【讨论】:

  • 谢谢。我会看看它。我们可以批量更新而不是一个吗?
  • 我们正在创建一个UpdateOneModel 列表,然后 mongo 驱动程序会将它们作为批量操作执行。当您需要对许多文档应用 same 更新时,使用 UpdateMulti。
  • 我们将 InsertOneModel 类作为映射的一部分。当我尝试用 ReplaceOneModel 替换时,它给出了未经检查的赋值的编译错误,因为它没有 Document 作为参数之一
  • 你用的是什么版本的mongo驱动?
  • 哦,我明白了。在ReplaceOneModel 的构造函数中,第一个文档是一个查询,它正在查找要替换的元素。如果要更新文档,则需要指定它,因为 mongo 驱动程序无法自行解决
猜你喜欢
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多