107

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

ndequeker
  • 7,932
  • 7
  • 61
  • 93
Tauquir
  • 6,613
  • 7
  • 37
  • 48

9 Answers9

117

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

Sinan
  • 11,443
  • 7
  • 37
  • 48
  • 107
    This indeed doesn't answer to `how to set one of my fields as primary key`, ex: i want user_email as key in user collections, but how to set that field as key and unique – Medet Tleukabiluly Apr 19 '15 at 06:01
  • 14
    How does this answers the question?? – Lokesh Sanapalli Nov 23 '18 at 05:46
  • The _id field is the default index and needs to be unique. Therefore, place the data that is your unique constraint into that field. (https://docs.mongodb.com/master/indexes/#default-id-index) – Steven Scott May 12 '20 at 17:35
30

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.

Ali
  • 21,572
  • 15
  • 83
  • 95
  • This is interesting. Any reason I couldn't use this on an "archive" collection to store old versions of my documents in another colllection? `{ _id: { _id: ...object id..., version: 4 }` – Robert Sep 08 '21 at 19:03
  • @Robert _id field are indexed and kept in memory, so basically you are keeping all documents of that collection in memory. – Ali Sep 09 '21 at 00:57
  • Well I'll trust Mongo DB to manage the "working set" of what gets put into memory. I was a bit more concerned about key constraints but I found my answer here: https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Index-Key-Limit – Robert Sep 09 '21 at 14:26
28

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.

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
amolgautam
  • 897
  • 10
  • 20
  • 4
    "The unique constraint on indexes ensures that only one document can have a value for a field in a collection. For sharded collections these unique indexes cannot enforce uniqueness because insert and indexing operations are local to each shard" --https://docs.mongodb.org/manual/tutorial/enforce-unique-keys-for-sharded-collections/ – JohnC Apr 11 '16 at 02:30
22

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

Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71
12

Simple you can use

db.collectionName.createIndex({urfield:1},{unique:true});
Soviut
  • 88,194
  • 49
  • 192
  • 260
Abhijit Chakra
  • 3,201
  • 37
  • 66
7

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.

Lakshmikant Deshpande
  • 826
  • 1
  • 12
  • 30
codiacTushki
  • 750
  • 1
  • 9
  • 22
5

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

Menuka Ishan
  • 5,164
  • 3
  • 50
  • 66
2

MongoDB > Tutorial > Create an auto incrementing field - Archive

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

Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • 23
    Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference. – kleopatra Aug 20 '13 at 11:16
  • 4
    Link is now broken, thus this answer is useless – PeterM Jul 11 '17 at 11:49
  • 2
    Downvoted, because the page now redirects to: https://docs.mongodb.com/manual/crud/ which mentions neither "auto" nor "increment". – mausworks Dec 13 '18 at 11:55
  • The link is broken as suggested in other comments. I updated the link and now it points to a snapshot of the page from 2013 Aug on The Wayback Machine. – Sagar V May 15 '21 at 11:47
2

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

CollectionName._ensureIndex({field:1 }, {unique: true});
Tincho825
  • 829
  • 1
  • 13
  • 15