spring-dataspring-data-mongodbproject-reactorbulkinsertspring-data-mongodb-reactive

Bulk Update with Spring Data MongoDB Reactive


How can I perform bulk perations using ReactiveMongoTemplate?

Basically I want to initialize bulk using db.<collection_name>.initializeUnorderedBulkOp() and execute it using <bulk>.execute().

I know there is a way to do this using simple MongoTemplate as specified here but I can't find any way how to do this in reactive.


Solution

  • I finally managed to perform bulk writing using MongoCollection.bulkWrite method.

    reactiveMongoTemplate.getCollection("assets_refs").flatMap(mongoCollection -> {
            var operations = entities.stream().map(entity -> {
                Document doc = new Document();
                reactiveMongoTemplate.getConverter().write(entity, doc);
                var filter = new Document("externalId", entity.getExternalId());
                return new UpdateOneModel<Document>(filter, new Document("$set", doc), new UpdateOptions().upsert(true));
            }).toList();
            return Mono.from(mongoCollection.bulkWrite(operations));
        })