16.7. Accessing the MongoDB Document ID Field

Problem

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

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

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.