Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we cannot define primary key ourself in mongodb?

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?

like image 945
vinson Avatar asked Feb 15 '23 19:02

vinson


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

like image 135
Dylan Tong Avatar answered Mar 03 '23 06:03

Dylan Tong