Mongodb – How to create unique IDs for embedded documents in MongoDB

mongodb

So I need to reference particular subdocuments uniquely from items in my collection. For instance:

User = {
    'name': 'jim',
    'documents: [
        {'id': 0001, 'title': "My document"},
        {'id': 0002, 'title': "My second document!"},
    ]
}

So I need to be able to auto-create IDs for new documents, preferably not at the application level (since there will be race conditions in the actual development scenario).

Is there a way to use mongo's autogenerated ObjectId (used in the _id field at the collection level), or something similar?

Best Answer

Yes, using mongo's ObjectId is the way to go. The only thing is: you have to generate them yourself, in the application code. They are meant to be globally unique, different workers won't generate two identical ObjectIds, so there's no race condition in that sense.

All official drivers should provide a way to generate ObjectId. Here's how it is in Ruby:

oid = BSON::ObjectId.new