MongoDB创建唯一索引

MongoDB创建唯一索引

MongoDB 中我们创建的索引时,如果希望某个字段的值只能是唯一的,那么我们可以使用唯一索引来约束该字段,在 MongoDB 中,创建唯一索引,可以使用 unique 参数。

MongoDB创建唯一索引详解

语法

db_name.table_name.createIndex({}, {unique:true})

参数

名称 描述
db_name 数据库名
table_name 集合名

说明

通过指定 unique 为 true,来创建唯一索引。

案例

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

19_MongoDB创建唯一索引.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insert 插入四条记录,具体命令如下:

db.haicoder.insert([ {id:1, "url" : "haicoder.net/c", "score" : 100 }, {id:2, "url" : "haicoder.net/cpp", "score" : 90 }, {id:3, "url" : "haicoder.net/golang", "score" : 80 }, {id:4, "url" : "haicoder.net/java", "score" : 60 } ]);

执行完毕后,此时,如下图所示:

20_MongoDB创建唯一索引.png

我们看到,此时提示我们成功插入了多条记录,现在,我们创建一个唯一索引,具体命令如下:

db.haicoder.ensureIndex({url:1}, {unique:true});

执行完毕后,此时,如下图所示:

21_MongoDB创建唯一索引.png

现在,我们查看当前的所有索引,具体命令如下:

db.haicoder.getIndexes()

执行完毕后,此时,如下图所示:

22_MongoDB创建唯一索引.png

我们看到,此时创建的 url 索引是唯一索引,现在,我们插入一条重复的 url,具体命令如下:

db.haicoder.insert({id:5, "url" : "haicoder.net/c", "score" : 100 });

执行完毕后,此时,如下图所示:

23_MongoDB创建唯一索引.png

我们看到,此时提示我们插入失败,url 字段重复了。

MongoDB创建唯一索引总结

在 MongoDB 中我们创建的索引时,如果希望某个字段的值只能是唯一的,那么我们可以使用唯一索引来约束该字段,在 MongoDB 中,创建唯一索引,可以使用 unique 参数。