How to set a primary key in MongoDB?

Mongodb

Mongodb Problem Overview


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

Mongodb Solutions


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

Solution 2 - Mongodb

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.

Solution 3 - Mongodb

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.

Solution 4 - Mongodb

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 }" } })

Solution 5 - Mongodb

Simple you can use

db.collectionName.createIndex({urfield:1},{unique:true});

Solution 6 - Mongodb

One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.

Solution 7 - Mongodb

This is the syntax of creating primary key

> db.< collection >.createIndex( < key and index type specification>, { > unique: true } )

Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.

db.student.createIndex({student_id:1},{unique:true})

You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.

prefer this document for further informations https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index

Solution 8 - Mongodb

MongoDB > Tutorial > Create an auto incrementing field - Archive

You can also check this link and auto-increment the _id field.

Solution 9 - Mongodb

If you're using Mongo on Meteor, you can use _ensureIndex:

CollectionName._ensureIndex({field:1 }, {unique: true});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTauquirView Question on Stackoverflow
Solution 1 - MongodbSinanView Answer on Stackoverflow
Solution 2 - MongodbamolgautamView Answer on Stackoverflow
Solution 3 - MongodbAliView Answer on Stackoverflow
Solution 4 - MongodbNanhe KumarView Answer on Stackoverflow
Solution 5 - MongodbAbhijit ChakraView Answer on Stackoverflow
Solution 6 - MongodbcodiacTushkiView Answer on Stackoverflow
Solution 7 - MongodbMenuka IshanView Answer on Stackoverflow
Solution 8 - Mongodbnancy guptaView Answer on Stackoverflow
Solution 9 - MongodbTincho825View Answer on Stackoverflow