Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a primary key in MongoDB?

Tags:

mongodb

I want to set one of my fields as primary key. I am using MongoDB as my NoSQL.

like image 237
Tauquir Avatar asked Jul 21 '10 12:07

Tauquir


People also ask

How do I set primary key in MongoDB schema?

_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.

Can we create primary key in MongoDB?

All documents in a MongoDB collection have a primary key dubbed _id . This field is automatically assigned to a document upon insert, so there's rarely a need to provide it. What's interesting about the _id field is that it is time based.

Does MongoDB use primary key and foreign key?

MongoDB ReferencesNormally, MongoDB doesn't work with the concept of foreign keys. The foreign keys can be used in the Relational Databases for visualizing data from multiple collections simultaneously.

What should be the default primary key in MongoDB for this document?

Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.


2 Answers

_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.

Additional info: http://www.mongodb.org/display/DOCS/BSON

Hope it helps.

like image 112
Sinan Avatar answered Oct 20 '22 01:10

Sinan


The other way is to create Indexes for your collection and make sure that they are unique.

You can find more on the following link

I actually find this pretty simple and easy to implement.

like image 42
amolgautam Avatar answered Oct 20 '22 01:10

amolgautam