Unique indexes ensure that a value appears at most once for a given field.唯一索引确保给定字段的值最多出现一次。
To create a unique index in the MongoDB Shell, use the 要在MongoDB Shell中创建唯一索引,请使用db.collection.createIndex() method with the unique option set to true.db.collection.createIndex()方法,并将unique选项设置为true。
db.collection.createIndex(
{ <field>: <sortOrder> },
{ unique: true }
)
About this Task关于此任务
This example adds a unique index on the 此示例在user_id field of a members collection to ensure that there are no duplicate values in the user_id field.members集合的user_id字段上添加了一个唯一索引,以确保user_id字段中没有重复值。
Steps步骤
To create a unique index on the 要在user_id field of the members collection, run the following command in mongosh:members集合的user_id字段上创建唯一索引,请在mongosh中运行以下命令:
db.members.createIndex( { "user_id": 1 }, { unique: true } )