Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MongoDB, do document _id's need to be unique across a collection or the entire DB?

Tags:

mongodb

I'm building a database with several collections. I have unique strings that I plan on using for all the documents in the main collection. Documents in other collections will reference documents in the main collection, which means I'll have to save said id's in the other collections. However, if _id's only need to be unique across a collection and not across an entire database, then I would just make the _id's in the other collections also use the aforementioned unique strings.

Also, I assume that in order to set my own _id's, all I have to do is have an "_id":"unique_string" property as part of the document that I insert, correct? I wouldn't need to convert the "unique_string" into another format, right?

Also, hypothetically speaking, would I be able to have a variable save the string "_id" and use that instead? Just to be clear, something as follows: var id = "_id" and then later on in the code (during an insert or a query for example) have id:"unique_string".

Best, and thanks,
Sami

like image 469
thisissami Avatar asked Aug 11 '11 23:08

thisissami


People also ask

Are MongoDB IDs unique across collections?

The uniqueness constraint for _id is per collection, so yes - one and the same ID can occur once per Collection. It's however very unlikely, if not impossible, for the same ID to be generated twice. So in order for this to happen you would have to manually insert duplicate IDs.

Are Objectids unique across collections?

Is MongoDB ObjectID Unique? According to MongoDB, ObjectID can be considered globally unique. The first nine bytes in a MongoDB _ID guarantee its uniqueness across machines and processes, in relation to a single second; the last three bytes provide uniqueness within a single second in a single process.

How does MongoDB ensure unique values?

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

How does a document relate to a collection in MongoDB?

Instead of tables, a MongoDB database stores its data in collections. A collection holds one or more BSON documents. Documents are analogous to records or rows in a relational database table. Each document has one or more fields; fields are similar to the columns in a relational database table.


1 Answers

_ids have to be unique in a collection. You can quickly verify this by inserting two documents with the same _id in two different collections.

Your other assumptions are correct, just try them and see whether they work (they will). The proof of the pudding is in the eating.

Note: use _id directly, var id = "_id" just compilcates the code.

like image 110
Karoly Horvath Avatar answered Sep 20 '22 12:09

Karoly Horvath