Docs Menu
Docs Home
/ / /
Java Sync
/ /

Replace a Document

You can replace a single document using the replaceOne() method on a MongoCollection object. This method removes all the existing fields and values from a document (except the _id field) and substitutes it with your replacement document.

The replaceOne() method accepts a query filter that matches the document you want to replace and a replacement document that contains the data you want to save in place of the matched document. The replaceOne() method only replaces the first document that matches the filter.

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

Upon successful execution, the replaceOne() method returns an instance of UpdateResult. You can retrieve information such as the number of documents modified by calling the getModifiedCount() method. You can also retrieve the value of the document's _id field by calling the getUpsertedId() method if you set upsert(true) in the ReplaceOptions instance and the operation resulted in the insertion of a new document.

If your replacement operation fails, the driver raises an exception. For example, if you try to specify a value for the immutable field _id in your replacement document that differs from the original document, the method throws a MongoWriteException with the message:

After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...)

If your replacement 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 replaceOne(), linked at the bottom of this page.

In this example, we replace the first match of our query filter in the movies collection of the sample_mflix database with a replacement document. All the fields except for the _id field are deleted from the original document and are substituted by the replacement document.

Before the replaceOne() operation runs, the original document contains several fields describing the movie. After the operation runs, the resulting document contains only the fields specified by the replacement document (title and fullplot) and the _id field.

The following snippet uses the following objects and methods:

  • A query filter that is passed to the replaceOne() method. The eq filter matches only movies with the title exactly matching the text 'Music of the Heart'.

  • A replacement document that contains the document that replaces the matching document if it exists.

  • A ReplaceOptions object with the upsert option set to true. This option specifies that the method should insert the data contained in the replacement document if the query filter does not match any documents.

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.

package usage.examples;
import static com.mongodb.client.model.Filters.eq;
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.ReplaceOptions;
import com.mongodb.client.result.UpdateResult;
public class ReplaceOne {
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");
Bson query = eq("title", "Music of the Heart");
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");
ReplaceOptions opts = new ReplaceOptions().upsert(true);
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId()); // only contains a value when an upsert is performed
} catch (MongoException me) {
System.err.println("Unable to replace 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 replaced document, it should look something like this:

Document {
{ _id=...,
title=50 Violins,
fullplot=A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music
}
}

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:

Back

Update Multiple Documents