The _id
field is reserved for primary key in mongodb
. But why mongodb
is designed like this? And can I define the primary key myself?
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 enforce uniqueness. Refer below: http://docs.mongodb.org/manual/tutorial/create-a-unique-index/
I'm not sure if I understand the why part of your question. As you mention _id is a primary key and serves the point of ensuring uniqueness of a document within a collection, and a means of retrieving documents by a unique id. It's purpose is no different from primary keys in other databases. Why is it pre-defined? It's partly due to the fact that MongoDB assigns a unique object Id value for you automatically if you don't specify one for that purpose. Having a standard _id field simplifies the implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With