Docs Menu
Docs Home
/ / /
Java Sync Driver
/ /

Update a Document

You can update a single document using the updateOne() 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 updateOne() method only updates the first document that matches the filter.

To perform an update with the updateOne() method, you must pass a query filter and an update document. The query filter specifies the criteria for which document to perform the update on and the update document provides instructions on what changes to make to it.

You can optionally pass an instance of UpdateOptions to the updateOne() method in order to specify the method's behavior. For example, if you set the upsert field of the UpdateOptions object to true, the operation inserts a new document from the fields in both the query and update document if no documents match the query filter. See the link to the UpdateOptions API documentation at the bottom of this page for more information.

Upon successful execution, the updateOne() method returns an instance of UpdateResult. You can retrieve information such as the number of documents modified by calling the getModifiedCount() method, or the value of the _id field by calling the getUpsertedId() method if you specified upsert(true) in an UpdateOptions instance.

If your update operation fails, the driver raises an exception. For example, if you try to set a value for the immutable field _id in your update document, the method 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 resembles the following:

E11000 duplicate key error collection: ...

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

In this example, we update the first match for our query in the movies collection of the sample_mflix database. We perform the following updates to the matching document:

  • Set the value of runtime to 99

  • Add Sports 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. For more information about the Updates builder, see our guide on the Updates builder.

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.

// Updates the first document that matches a query filter by using the Java driver
package usage.examples;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateOne {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Document query = new Document().append("title", "Cool Runnings 2");
// Creates instructions to update the values of three document fields
Bson updates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));
// Instructs the driver to insert a new document if none match the query
UpdateOptions options = new UpdateOptions().upsert(true);
try {
// Updates the first document that has a "title" value of "Cool Runnings 2"
UpdateResult result = collection.updateOne(query, updates, options);
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
}
}
}

After you run the example, you should see output that looks something like this:

Modified document count: 1
Upserted id: null

Or if the example resulted in an upsert:

Modified document count: 0
Upserted id: BsonObjectId{value=...}

If you query the updated document, the output resembles the following:

Document {
{ _id=...,
plot=...,
genres=[Adventure, Comedy, Family, Sports],
runtime=99,
...
lastUpdated=Timestamp{...}
}
}

Tip

Legacy API

If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.

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

  • UpdateOne

  • UpdateOptions

  • combine()

  • set()

  • addToSet()

  • currentTimestamp()

  • UpdateResult

Back

Update & Replace Operations