Get the App
SLTechnology News&Howtos  ›  Database  › 

[MongoDB Learning Notes 25] Index type of MongoDB

Shulou Source: shulou.com Published: 2022-06-01 17:59:51 10月02日 Update

创建索引可以指定一些选项,使用不同的选项建立的索引会有不同的行为。

一、唯一索引

唯一索引可以确保每一个文档的指定键都有唯一的值。例如,想确定文档中的username键不重复,创建一个唯一索引:

> db.users.findOne() { "_id" : ObjectId("54ad5826245d1b7d58b53238"), "i" : 2, "username" : "user2", "age" : 39, "created" : ISODate("2015-01-07T16:00:38.634Z") }> db.users.ensureIndex({"username":1},{"unique":true}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

> db.users.insert({"username":"user2"}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: blog.users.$username_1 dup key: { : \"user2\" }" } }) >

可以看出创建唯一索引后,就不能插入相同的键值;

1.唯一复合索引

创建唯一复合索引,复合索引的单键值可以重复,但是组成唯一复合索引的组合键值只能唯一。例如:

如果有一个{"username":"user2","age":18}有唯一的索引,下面的插入是合法的,

>db.users.insert({"username":"bob"})>db.users.insert({"username":"bob","age":23})>db.users.insert({"username":"fred","age":23})

如果再次插入这三项中的任意一个,会导致键重复异常;

2.去重复

对于已经有重复值的字段上创建唯一索引,会引起错误;可以使用dropDups选项遇到重复值会保留第一个,删除其他重复项;

>db.users.ensureIndex({"username":1},{"unique":true,"dropDups":true})

慎用这个选项,因为根本没有办法控制删除哪些文档;

二、稀疏索引

如果有一个可能存在也有可能不存在的字段,在此字段上创建的索引称为稀疏索引。

创建唯一稀疏索引:

>db.users.ensureIndex({"username":1},{"unique":true,"sparse":true})

创建非唯一稀疏索引:

>db.users.ensureIndex({"username":1},{"sparse":true})

Tags: Index sparse field document different legal same again method single key fundamental behavior error faceted non-exclusive control combination notes type learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei OPPO Reno Shulou Information Shulou Technology