简体   繁体   English

Spring 数据 MongoDB - 插入批量跳过重复项

[英]Spring data MongoDB - Insert batch skip duplicates

I want to save 1000+ entries in batch, ignoring the duplicates我想批量保存 1000 多个条目,忽略重复项

@Document("contacts")
@Data
@CompoundIndex(name = "unique_name_number", unique = true, def = "{'name' : 1, 'phoneNumber' : 1 }")
@AllArgsConstructor
public class ContactModel {

    @Id
    String id;

    Instant createdAt;
    String name;
    String phoneNumber;

}

And the execution和执行

MongoTemplate mongo;
List<ContactModel> contacts = getLongList()
mongo.insert(contacts, ContactModel.class)

This code throws an exception if there are duplicates (name,phoneNumber).如果有重复项(姓名、电话号码),此代码将引发异常。

How can I tell to mongo我怎么能告诉 mongo

Skip the duplicates and continue to insert the rest?跳过重复项,继续插入 rest?

Thanks much非常感谢

You can try, using an unordered BulkOperations , like this:您可以尝试使用无序的BulkOperations ,如下所示:

BulkOperations bulkOps = mongo.bulkOps(BulkMode.UNORDERED, ContactModel.class);
bulkOps.insert(contacts);
BulkWriteResult results = bulkOps.execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM