Docs Menu
Docs Home
/ / /
Scala
/ /

Bulk Write Operations

There are two types of bulk operations, ordered and unordered bulk operations:

  1. Ordered bulk operations execute all the operations in order and error out on the first write error.

  2. Unordered bulk operations execute all the operations and report any the errors. Unordered bulk operations do not guarantee an order of execution.

Note

This guide uses the Observable implicits as covered in the Quick Start Primer.

The following code provides examples using ordered and unordered operations:

import org.mongodb.scala._
import org.mongodb.scala.model._
// Ordered bulk operation - order is guaranteed
collection.bulkWrite(
List(InsertOneModel(Document("_id" -> 4)),
InsertOneModel(Document("_id" -> 5)),
InsertOneModel(Document("_id" -> 6)),
UpdateOneModel(Document("_id" -> 1), Document("$set", Document("x" -> 2))),
DeleteOneModel(Document("_id" -> 2)),
ReplaceOneModel(Document("_id"-> 3), Document("_id" -> 3, "x" -> 4)))
).printResults()
// Unordered bulk operation - no guarantee of order of operation
collection.bulkWrite(
List(InsertOneModel(Document("_id" -> 4)),
InsertOneModel(Document("_id" -> 5)),
InsertOneModel(Document("_id" -> 6)),
UpdateOneModel(Document("_id" -> 1), Document("$set", Document("x" -> 2))),
DeleteOneModel(Document("_id" -> 2)),
ReplaceOneModel(Document("_id"-> 3), Document("_id" -> 3, "x" -> 4))),
BulkWriteOptions().ordered(false)
).printResults()

Back

Write Operations