Get the App
SLTechnology News&Howtos  ›  Database  › 

How to use unique Index in MongoDB

Shulou Source: shulou.com Published: 2022-05-31 21:13:41 09月22日 Update

This article will explain in detail how to use the unique index in MongoDB. The content of the article is of high quality. Therefore, Xiaobian shares it with you as a reference. I hope you have a certain understanding of relevant knowledge after reading this article.

The primary purpose of a unique index is to use it on a field so that the contents of that field are not duplicated.

Example: Creating a Unique Index

> db.emp.createIndex({"name":1},{"unique":true})

{

"createdCollectionAutomatically" : false,

"numIndexesBefore" : 1,

"numIndexesAfter" : 2,

"ok" : 1

}

Duplication is not allowed in the name field.

Example: Adding name duplicate data to emp collection

> db.emp.insert({"name":"king","sex":"male","age":35,"sal":8000,"loc":"Beijing"});

WriteResult({

"nInserted" : 0,

"writeError" : {

"code" : 11000,

"errmsg" : "E11000 duplicate key error collection: hr.emp index: name_1 dup key: { : \" Wangba\" }"

}

})

The above error message occurs because a unique index is set on the name field.

About how to use the unique index in MongoDB to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Index content field article more son of a bitch knowledge article example good information data purpose quality error Beijing reference help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft macOS Linux Redmi Huawei