开发者

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

开发者 https://www.devze.com 2023-03-27 07:10 出处:网络
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 t

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


_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消