Gaurav Abbi Gaurav Abbi - 1 year ago 154
Scala Question

How to get the document object id after insert in reactivemongo?

I have seen that this question seems to have been asked earlier (almost 3 years ago), but since then there might be lot of changes in the reactive mongo library.

I am using the play plugin with version 2.4, but the reactivemongo.api.commands.WriteResult does not seem to have any API to get the document object id.

Now I can start setting the object id by myself, but I do not find it a convincing and right idea since some value unique on the machine where I create the id might not be same with the other machine and to keep things simple I want to let this being handled by mongo db.

So yeah if there is some way that I can get the id of the inserted document will be great or else I have to fallback to the way to setting the id by myself which I something I am trying to avoid.

Answer Source

Creating ObjectId on the client side is fine. It's what casbah (a blocking MongoDB driver for MongoDB) is doing if you dig into its code.

If you take a look at ObjectId fields, then you'll find a 3-byte machine identifier among others. It's calculated tricky (involving InetAddress in standard Java driver). It guarantees that there cannot be a collision between 2 ObjectIds, generated at the same time on different machines.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download