Docs Home / Indexes / Properties / Unique

Create a Single-Field Unique Index创建单个字段唯一索引

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 db.collection.createIndex() method with the unique option set to true.要在MongoDB Shell中创建唯一索引,请使用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 } )

Learn More了解更多