无法使用bulkwrite更新mongo集合

vshtjzan  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(437)

我有一个mongo集合,包含以下字段
sno2位置
集合中的数据格式为

  1. Sno1 Sno2 Location
  2. --------------------------------
  3. 1000 2000 Hyderabad

我想把地点更新成“金奈”。当我对mongocollection类使用bulkwrite方法时,它返回以下异常

  1. Here is the snippet
  2. mongoColl.bulkWrite(docs, writeOptions); --> docs is List<InsertOneModel<Document>>
  3. BulkWriteError(index=0, code=11000, message='E11000 duplicate key error collection'

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

8zzbczxx

8zzbczxx1#

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

  1. MongoDatabase db = client.getDatabase("test");
  2. MongoCollection<Document> collection = db.getCollection("test");
  3. List<UpdateOneModel<Document>> updateList = List.of(
  4. new UpdateOneModel<>(new Document(Map.of("col1", "val1")), Updates.set("field", "1")),
  5. new UpdateOneModel<>(new Document(Map.of("col1", "val2")), Updates.set("field", "2")));
  6. BulkWriteOptions options = new BulkWriteOptions().ordered(false);
  7. collection.bulkWrite(updateList, options);

如果你需要一种上进的行为,你可以使用 com.mongodb.client.model.ReplaceOneModelReplaceOptions.upsert(true) :

  1. ReplaceOptions replaceOptions = new ReplaceOptions().upsert(true);
  2. List<ReplaceOneModel<Document>> replaceList = List.of(
  3. new ReplaceOneModel<>(new Document(Map.of("col1", "val3")), new Document(Map.of("col1", "val3", "field", "1")), replaceOptions),
  4. new ReplaceOneModel<>(new Document(Map.of("col1", "val4")), new Document(Map.of("col1", "val4", "field", "2")), replaceOptions));
  5. collection.bulkWrite(replaceList, options);
展开查看全部

相关问题