Docs Menu
Docs Home
/ / /
Scala

Write Data to MongoDB

On this page

  • Overview
  • Sample Application
  • Insert One
  • Insert Multiple
  • Update One
  • Update Multiple
  • Replace One
  • Delete One
  • Delete Multiple
  • Bulk Write

On this page, you can see copyable code examples that show common methods you can use to write data to MongoDB by using the Scala driver.

Tip

To learn more about any of the methods shown on this page, see the link provided in each section.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string URI>, with the relevant values for your MongoDB deployment.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have the Scala driver installed in your Maven or sbt project.

  2. Copy the following code and paste it into a new .scala file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

1import org.mongodb.scala._
2import org.mongodb.scala.bson.Document
3import org.mongodb.scala.model._
4import org.mongodb.scala.model.Filters._
5import org.mongodb.scala.result._
6import org.mongodb.scala.model.Updates._
7
8object SampleWriteApp {
9
10 def main(args: Array[String]): Unit = {
11 val mongoClient = MongoClient("<connection string URI>")
12 val database: MongoDatabase = mongoClient.getDatabase("<database name>")
13 val collection: MongoCollection[Document] = database.getCollection("<collection name>")
14
15 // Start example code here
16
17 // End example code here
18
19 // Wait for the operations to complete before closing client
20 // Note: This example uses Thread.sleep() for brevity and does not guarantee all
21 // operations will be completed in time
22 Thread.sleep(1000)
23 mongoClient.close()
24 }
25}

The following code shows how to insert a single document into a collection:

val doc: Document = Document("<field name>" -> "<value>")
val observable: Observable[InsertOneResult] = collection.insertOne(doc)
observable.subscribe(new Observer[InsertOneResult] {
override def onNext(result: InsertOneResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the insertOne() method, see the Insert Documents guide.

The following code shows how to insert multiple documents into a collection:

val docs: Seq[Document] = Seq(
Document("<field name>" -> "<value>"),
Document("<field name>" -> "<value>")
)
val observable: Observable[InsertManyResult] = collection.insertMany(docs)
observable.subscribe(new Observer[InsertManyResult] {
override def onNext(result: InsertManyResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the insertMany() method, see the Insert Documents guide.

The following code shows how to update a single document in a collection by creating or editing a field:

val filter = equal("<field to match>", "<value to match>")
val update = set("<field name>", "<value>")
val observable: Observable[UpdateResult] = collection.updateOne(filter, update)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the updateOne() method, see the Update Documents guide.

The following code shows how to update multiple documents in a collection by creating or editing a field:

val filter = equal("<field to match>", "value to match")
val update = set("<field name>", "<value>")
val observable: Observable[UpdateResult] = collection.updateMany(filter, update)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the updateMany() method, see the Update Documents guide.

The following code shows how to replace a single document in a collection with a new document:

val filter = equal("<field to match>", "<value to match>")
val replacementDoc: Document = Document("<field name>" -> "<value>")
val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacementDoc)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the replaceOne() method, see the Replace Documents guide.

The following code shows how to delete a single document in a collection:

val filter = equal("<field to match>", "<value to match>")
val observable: Observable[DeleteResult] = collection.deleteOne(filter)
observable.subscribe(new Observer[DeleteResult] {
override def onNext(result: DeleteResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the deleteOne() method, see the Delete Documents guide.

The following code shows how to delete multiple documents in a collection:

val filter = equal("<field to match>", "<value to match>")
val observable: Observable[DeleteResult] = collection.deleteMany(filter)
observable.subscribe(new Observer[DeleteResult] {
override def onNext(result: DeleteResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the deleteMany() method, see the Delete Documents guide.

The following code shows how to perform multiple write operations in a single bulk operation:

val operations = Seq(
InsertOneModel(Document("<field name>" -> "<value>")),
UpdateManyModel(equal("<field to match>", "<value to match>"), set("<field name>", "<value>")),
DeleteOneModel(equal("<field to match>", "<value to match>"))
)
val observable: Observable[BulkWriteResult] = collection.bulkWrite(operations)
observable.subscribe(new Observer[BulkWriteResult] {
override def onNext(result: BulkWriteResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})

To learn more about the bulkWrite() method, see the Bulk Write Operations guide.

Back

Monitor Changes