In MongoDB, does document_id need to be unique in the collection or the entire database?

I am creating a database with several collections. I have unique lines that I plan to use for all documents in the main collection. Documents in other collections will refer to documents in the main collection, which means that I will have to save the specified identifier in other collections. However, if _id only needs to be unique in the collection, and not across the entire database, then I will simply make _id in other collections also use the above unique strings.

Also, I assume that in order to set my own _id, all I have to do is have the property "_id":"unique_string" as part of the document that I am inserting, right? I would not need to convert "unique_string" to another format, right?

Also, hypothetically speaking, can I have a variable storing the string "_id" and use it instead? To be clear, something like this: var id = "_id" , and then in the code (during insertion or request, for example) is id:"unique_string" .

Best and thanks
Themselves

+6
source share
1 answer

_id must be unique in the collection. You can quickly check this by inserting two documents with the same _id into two different collections.

Your other assumptions are true, just try them and see if they will work (they will). The proof of the pudding is food.

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

+9
source

Source: https://habr.com/ru/post/894889/


All Articles