Scala: How to access the MongoDB document ‘_id’ field with Casbah

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 16.7, “How to access the MongoDB document ‘ID’ field (_id) with Casbah.”

Problem

You want to get the ID field for a document you’ve inserted into a MongoDB collection in a Scala application.

Solution

Perform a query to get the document you want, and then call get("_ID") on the resulting MongoDBObject, like this:

basicDbObject.get("_id")

The following example shows how to get the ID field from a DBObject after inserting the object into the database. I first create a Stock as usual, convert the Stock to a MongoDBObject, perform the insert, and then get the ID value, which is added to the MongoDBObject after the insert operation is performed:

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

object InsertAndGetId extends App {
    val coll = MongoFactory.collection
    // get the _id field after an insert
    val amazon = Stock("AMZN", 220)
    val amazonMongoObject = buildMongoDbObject(amazon)
    coll.insert(amazonMongoObject)
    println("ID: " + amazonMongoObject.get("_id"))
}

If you just need to get the ID field from a MongoDBObject after performing a query, the following complete example shows how to do that with a match expression:

import com.mongodb.casbah.Imports._

object GetId extends App {
    val collection = MongoFactory.collection
    val query = MongoDBObject("symbol" -> "GOOG")
    collection.findOne(query) match {
        case Some(result) => println("ID: " + result.get("_id"))
        case None => println("Stock not found")
    }
}

A match expression is used in this example because the findOne(query) will return None if no matching documents are found in the collection. You can also use the usual getOrElse and foreach techniques to work with an Option.

If you’ve been following along with the MongoDB recipes in this chapter, save those files with the names InsertAndGetId.scala and GetId.scala in the root directory of your project, and run them with sbt run.

See Also

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.