Why can't we define the primary key in mongodb?

The _id field _id reserved for the primary key in mongodb . But why is mongodb designed like this? And can I determine the primary key myself?

+4
source share
2 answers

Yes, you can define your own primary key for your collection. Note that MongoDB drivers automatically generate unique _id values; however, you can override this _id value:

eg. db.yourcollection.insert ({_ ID: "myuniquevalueN", a: 1, b: 1})

You can also create secondary indexes that provide uniqueness. See below: http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

I'm not sure if I understand why part of your question. As you say, _id is the primary key and serves to ensure the uniqueness of the document in the collection and the means to obtain documents by a unique identifier. Its purpose is no different from primary keys in other databases. Why is this predefined? This is partly due to the fact that MongoDB automatically assigns a unique value to the object identifier if you do not specify it for this purpose. Having a standard _id field simplifies implementation.

+6
source

_ID must be unique. Since Mongodb nodes can be geographically distributed, the goal is to minimize any potential chance of a collision.

+2
source

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


All Articles