How to set a primary key in MongoDB?

前端 未结 9 987
再見小時候
再見小時候 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:18

    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 creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.

提交回复
热议问题