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.”


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


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.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.