Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Update Multiple Documents

You can update multiple documents using the updateMany() method on a MongoCollection object. The method accepts a filter that matches the document you want to update and an update statement that instructs the driver how to change the matching document. The updateMany() method updates all the documents in the collection that match the filter.

To perform an update with the updateMany() method, you must pass a query filter and an update document. The query filter specifies which documents in the collection to match and the update document provides instructions on what changes to make to them.

You can optionally pass an instance of UpdateOptions to the updateMany() method in order to modify the behavior of the call. For example, if you set the upsert field of the UpdateOptions object to true and no documents match the specified query filter, the operation inserts a new document composed of the fields from both the query and update document.

Upon successful execution, the updateMany() method returns an instance of UpdateResult. You can retrieve information such as the number of documents modified by calling the getModifiedCount() method. If you specified upsert(true) in an UpdateOptions object and the operation results in an insert, you can retrieve the _id field of the new document by calling the getUpsertedId() method on the UpdateResult instance.

If your update operation fails, the driver raises an exception and does not update any of the documents matching the filter. For example, if you try to set a value for the immutable field _id in your update document, the updateMany() method does not update any documents and throws a MongoWriteException with the message:

Performing an update on the path '_id' would modify the immutable field '_id'

If your update document contains a change that violates unique index rules, the method throws a MongoWriteException with an error message that should look something like this:

E11000 duplicate key error collection: ...

For more information on the types of exceptions raised under specific conditions, see the API documentation for updateMany(), linked at the bottom of this page.

In this example, we use a Filter builder to filter our query for movies in the genre "Frequently Discussed".

Next, we update documents that match our query in the movies collection of the sample_mflix database. We perform the following updates to the matching documents:

  • Add Frequently Discussed to the array of genres only if it does not already exist

  • Set the value of lastUpdated to the current time.

We use the Updates builder, a factory class that contains static helper methods to construct the update document. While you can pass an update document instead of using the builder, the builder provides type checking and simplified syntax. Read our guide on Updates in the Builders section for more information.

Note

This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

import com.mongodb.MongoException
import com.mongodb.client.model.Filters
import com.mongodb.client.model.Updates
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import java.time.LocalDateTime
data class Movie(
val num_mflix_comments: Int,
val genres: List<String>,
val lastUpdated: LocalDateTime
)
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
val query = Filters.gt(Movie::num_mflix_comments.name, 50)
val updates = Updates.combine(
Updates.addToSet(Movie::genres.name, "Frequently Discussed"),
Updates.currentDate(Movie::lastUpdated.name)
)
try {
val result = collection.updateMany(query, updates)
println("Modified document count: " + result.modifiedCount)
} catch (e: MongoException) {
System.err.println("Unable to update due to an error: $e")
}
mongoClient.close()
}
Modified document count: 53

After you run the example, you should see a similar output.

If you query the updated document or documents, they should look something like this:

Movie(num_mflix_comments=100, genres=[ ... Frequently Discussed], lastUpdated= ... )

For additional information on the classes and methods mentioned on this page, see the following API Documentation:

  • UpdateMany

  • UpdateOptions

  • combine()

  • addToSet()

  • currentDate()

  • UpdateResult

Back

Update a Document