How to set a primary key in MongoDB?
_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.
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.
In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.
But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:
{ _id : { a : 1, b: 1} }
Just be careful when using object as ids, the order of keys (a and b in the example) matters, if you swap them, it is considered a different id.
If you thinking like RDBMS, you can't create primary key. Default primary key is _id. But you can create Unique Index. Example is bellow.
db.members.createIndex( { "user_id": 1 }, { unique: true } )
db.members.insert({'user_id':1,'name':'nanhe'})
db.members.insert({'name':'kumar'})
db.members.find();
Output is bellow :
{ "_id" : ObjectId("577f9cecd71d71fa1fb6f43a"), "user_id" : 1, "name" : "nanhe" }
{ "_id" : ObjectId("577f9d02d71d71fa1fb6f43b"), "name" : "kumar" }
When you try to insert same user_id mongodb throws a write error.
db.members.insert({'user_id':1,'name':'aarush'})
WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: student.members index: user_id_1 dup key: { : 1.0 }" } })