Docs Menu
Docs Home
/ / /
Scala
/

Replace Documents

On this page

  • Overview
  • Sample Data
  • Replace Operation
  • Required Parameters
  • Replace One Document
  • Customize the Replace Operation
  • Return Value
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the Scala driver to perform a replace operation on a document in a MongoDB collection. A replace operation removes all fields and values from a specified document except the _id field, and adds new fields and values that you specify. This operation differs from an update operation, which changes only specified fields in one or more documents.

To learn more about update operations, see the Update Documents guide.

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your Scala application, create a MongoClient object that connects to an Atlas cluster and assign the following values to your database and collection variables:

val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

You can perform a replace operation in MongoDB by using the replaceOne() method. This method removes all fields except the _id field from the first document that matches the specified query filter. It then adds the fields and values you specify to the empty document.

You must pass the following parameters to the replaceOne() method:

  • Query filter, which matches which documents to update. To learn more about query filters, see the Specify a Query guide.

  • Replacement document, which specifies the fields and values that you want to replace the existing fields and values with.

The following example uses the replaceOne() method to replace the fields and values of a document in which the value of the name field is "Primola Restaurant":

val filter = equal("name", "Primola Restaurant")
val replacement = Document(
"name" -> "Frutti Di Mare",
"borough" -> "Queens",
"cuisine" -> "Seafood",
"owner" -> "Sal Thomas"
)
val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}")
override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}")
override def onComplete(): Unit = println("Completed")
})
Replaced document count: 1
Completed

Important

The value of the _id field is immutable. If your replacement document specifies a value for the _id field, it must be the same as the _id value of the existing document or the driver raises a WriteError.

The replaceOne() method optionally accepts a parameter with the ReplaceOptions data type. The ReplaceOptions class contains setter methods that you can use to configure the replace option. If you don't specify any options, the driver performs the replace operation with default settings.

The following table describes the setter methods in the ReplaceOptions class:

Method
Description

upsert()

Specifies whether the replace operation performs an upsert operation if no documents match the query filter. For more information, see upsert behavior in the MongoDB Server manual.
Defaults to false.

sort()

Sets the sort criteria to apply to the operation. If multiple documents match the query filter that you pass to the replaceOne() method, the operation replaces the first result. You can set this option to apply an order to matched documents to have more control over which document is replaced.

bypassDocumentValidation()

Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.
Defaults to false.

collation()

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

hint()

Sets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.

let()

Provides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields.

comment()

Sets a comment to attach to the operation.

The following code sets the upsert option to true, which instructs the driver to insert a new document that has the fields and values specified in the replacement document if the query filter doesn't match any existing documents:

val options = ReplaceOptions().upsert(true)
val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement, options)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}")
override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}")
override def onComplete(): Unit = println("Completed")
})
Replaced document count: 1
Completed

The replaceOne() method returns an UpdateResult object. You can use the following methods to access information from an UpdateResult instance:

Method
Description

getMatchedCount()

Returns the number of documents that matched the query filter.

getModifiedCount()

Returns the number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.

wasAcknowledged()

Returns true if the server acknowledged the result.

getUpsertedId()

Returns the _id value of the document that the driver upserted into the database, if any.

To view a runnable code example that demonstrates how to replace a document, see Write Data to MongoDB.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Insert