Kevin Meredith
Kevin Meredith

Reputation: 41939

Inserting Object into Mongo with _id Output

How can I insert a new object into Mongo and get the _id with the inserted document?

Desired behavior:

val _id: String = coll.insert(someObj) // _id = "_id" of inserted doc

Upvotes: 1

Views: 1339

Answers (1)

Alex K
Alex K

Reputation: 844

You don't have to look for it. When you insert a new object it's ID is generated on the client side, that means you know it already before sending.

From here: http://docs.mongodb.org/manual/reference/object-id/

ObjectId is a 12-byte BSON type, constructed using:

a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and a 3-byte counter, starting with a random value.

So, when you request to insert a new document, you will specify it already. Usually you either use existing ID, or you generate a new one using BSONObjectID.generate.

Here is a quick draft using a custom class for mapping(in this example I was using reactivemongo, not casbah):

case class Account(
  id: Option[BSONObjectID],
  firstName: String,
  lastName: String)

And then you do the following in your writer:

implicit object AccountBSONWriter extends BSONDocumentWriter[Account] {
  def write(account: Account): BSONDocument =
    BSONDocument(
      "_id" -> account.id.getOrElse(BSONObjectID.generate),
      "first_name" -> account.firstName,
      "last_name" -> account.lastName)
}

Upvotes: 4

Related Questions