How to set a primary key in MongoDB?

前端 未结 9 974
再見小時候
再見小時候 2020-12-07 21:46

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

相关标签:
9条回答
  • 2020-12-07 22:34

    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

    0 讨论(0)
  • 2020-12-07 22:36

    Simple you can use

    db.collectionName.createIndex({urfield:1},{unique:true});
    
    0 讨论(0)
  • 2020-12-07 22:39

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

    0 讨论(0)
提交回复
热议问题