如何在 MongoDB 中设置主键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3298963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:46:07  来源:igfitidea点击:

How to set a primary key in MongoDB?

mongodb

提问by Tauquir

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

我想将我的字段之一设置为主键。我使用MongoDB作为我的 NoSQL。

回答by Sinan

_idfield is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _idit will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.

_idfield 是为 mongodb 中的主键保留的,它应该是一个唯一的值。如果你没有设置任何东西,_id它会自动用“MongoDB Id Object”填充它。但是您可以将任何唯一信息放入该字段。

Additional info: http://www.mongodb.org/display/DOCS/BSON

附加信息:http: //www.mongodb.org/display/DOCS/BSON

Hope it helps.

希望能帮助到你。

回答by amolgautam

The other way is to create Indexesfor your collection and make sure that they are unique.

另一种方法是Indexes为您的收藏创建并确保它们是独一无二的。

You can find more on the following link

您可以在以下链接中找到更多信息

I actually find this pretty simple and easy to implement.

我实际上发现这非常简单且易于实现。

回答by Ali

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.

在 mongodb 中 _id 字段是为主键保留的。如果您没有在对象中定义它并创建索引以确保性能,Mongodb 将使用内部 ObjectId 值。

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 设置您自己的唯一值,Mongodb 将使用它而不是为您创建一个。即使您想使用多个字段作为主键,您也可以使用一个对象:

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

在创建这些 id 时要小心,键的顺序(示例中的 a 和 b)很重要,如果你交换它们,它被认为是一个不同的对象。

回答by Nanhe Kumar

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.

如果你像 RDBMS 一样思考你不能创建主键,默认主键是 _id。但是您可以创建Unique Index。示例如下。

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("577f9cecd71d71fa1fb6f43a"), "user_id" : 1, "name" : "nanhe" }

{ "_id" : ObjectId("577f9d02d71d71fa1fb6f43b"), "name" : "kumar" }

{“_id”:ObjectId(“577f9d02d71d71fa1fb6f43b”),“名称”:“库马尔”}

When you try to insert same user_id mongodb trow write error.

当您尝试插入相同的 user_id mongodb trow 写入错误时。

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

WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 重复键错误集合: student.members 索引: user_id_1 dup key: { : 1.0 }" } })

回答by Abhijit Chakra

Simple you can use db.collectionName.createIndex({urfield:1},{unique:true});

简单你可以使用 db.collectionName.createIndex({urfield:1},{unique:true});

回答by codiacTushki

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_idas the primary key then at the time of creating document in MongoDB; assign _idvalue same as that of employee_id.

实现此行为的一种方法是_id根据要视为主键的自定义字段将值设置为(为 MongoDB 中的主键保留)字段。
即如果我想employee_id作为主键,那么在 MongoDB 中创建文档时;赋值_id与 相同employee_id

回答by nancy gupta

http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

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

您还可以检查此链接并自动增加该_id字段。

回答by Menuka Ishan

This is the syntax of creating primary key

这是创建主键的语法

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

db.<集合>.createIndex(<键和索引类型说明>,{unique:true})

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

让我们假设我们的数据库有一个名为student 的集合,它的文档有一个名为student_id 的键,我们需要它来做一个主键。然后命令应该如下所示。

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

You can check whether this student_idset as primary key by trying to add duplicate value to the studentcollection.

您可以通过尝试向学生集合添加重复值来检查此student_id是否设置为主键。

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

更喜欢本文档以获取更多信息 https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index

回答by Tincho825

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

如果你在 Meteor 上使用 Mongo,你可以使用_ensureIndex

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