1

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

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

4

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)
}
Community
  • 1
  • 1
Alex K
  • 854
  • 9
  • 16
  • But, if it's generated at the client-side, then it's *possible* to create a non-unique value, right? – Kevin Meredith Sep 17 '13 at 01:22
  • That's correct. GUIDs and other UNIQUE identifiers are never unique as well, they use Mac address for example to generate unique ID, however if someone sets the same Mac then you might have the same value. However they also use time, date, etc. This makes it almost impossible to be non-unique. Same for MongoDB, possibility that you will have identical hardware in your cluster is extremely rare, if not impossible. I would need to look into their source code to find what exactly they use as a machine identifier but I think this is pretty reliable. There are websites with billions of records... – Alex K Sep 17 '13 at 03:02