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