Scala: How to update documents in a MongoDB collection with Casbah

This is an excerpt from the Scala Cookbook. This is Recipe 16.6, “How to update documents in a MongoDB collection with Casbah.”

Problem

You want to update one or more documents in a MongoDB collection in a Scala application.

Solution

Use either the findAndModify or update methods from the Casbah MongoCollection class, as shown in this example:

import com.mongodb.casbah.Imports._
import Common._

object Update extends App {
    val collection = MongoFactory.collection

    // -------------
    // findAndModify
    // -------------

    // create a new Stock object
    val google = Stock("GOOG", 500)

    // search for an existing document with this symbol
    var query = MongoDBObject("symbol" -> "GOOG")

    // replace the old document with one based on the 'google' object
    val res1 = collection.findAndModify(query, buildMongoDbObject(google))
    println("findAndModify: " + res1)

    // ------
    // update
    // ------

    // create a new Stock
    var apple = Stock("AAPL", 1000)

    // search for a document with this symbol
    query = MongoDBObject("symbol" -> "AAPL")

    // replace the old document with the 'apple' instance
    val res2 = collection.update(query, buildMongoDbObject(apple))
    println("update: " + res2)
}

In both cases, you build a document object to replace the existing document in the database, and then create a query object, which lets you find what you want to replace. Then you call either findAndModify or update to perform the update.

For instance, in the findAndModify example, a new Stock instance named google is created, and it’s used to replace the old document in the database whose symbol is GOOG. The buildMongoDbObject method is used to convert the google instance into a MongoDB document before the update method is called.

The difference between the two methods can be seen in the output:

findAndModify: Some({ "_id" : { "$oid" : "502683283004b3802ec47df3"}, "symbol" : "GOOG" , "price" : 500.0})
update: N/A

Whereas the findAndModify method returns the old document (the document that was replaced), the update method returns a WriteResult instance.

If you’ve been following along with the MongoDB recipes in this chapter, save that file as Update.scala in the root directory of your project, and run it with sbt run.