Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create unique IDs for embedded documents in MongoDB?

Tags:

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?

like image 978
Dan Avatar asked Apr 13 '12 16:04

Dan


People also ask

How does MongoDB generate unique ids?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record.

How do I set unique fields in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

Are MongoDB IDS unique?

By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements.

Do you need IDS in MongoDB?

All documents in MongoDB must have a populated _id field. If a document hasn't been assigned an _id value, MongoDB will automatically generate one.


2 Answers

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 
like image 195
Sergio Tulentsev Avatar answered Oct 05 '22 22:10

Sergio Tulentsev


All drivers have functionality for generating ObjectIds.

In the shell you just do new ObjectId():

> db.test.insert({x:new ObjectId()}); > db.test.find(); { "_id" : ObjectId("4f88592a06c05e4de90d0bc1"), "x" : ObjectId("4f88592a06c05e4de90d0bc0") } 

In Java it's new ObjectId() as well. See the API docs for your driver to see the specific syntax.

like image 39
Eve Freeman Avatar answered Oct 05 '22 21:10

Eve Freeman