JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Unique Index in MongoDB

Author:JIYIK Last Updated:2025/04/28 Views:

In this article, you'll learn about unique indexes, including what they are and how to create them in MongoDB. Additionally, the process of making a user's email unique in MongoDB is briefly described.

The contents of this article are as follows:

  1. Unique Index in MongoDB
  2. Creating a unique index in MongoDB
  3. Behavior of unique indexes in MongoDB
  4. Validating unique emails using Mongoose

Unique Index in MongoDB

A unique index ensures that the indexed field does not contain duplicate values, ensuring that the indexed field is unique. During collection construction, MongoDB generates a unique index on the _id column by default.

Use db.collection.createIndex()the command to generate a unique index and set the unique option to true.

db.collection.createIndex( <key and index type specification>, { unique: true } )

Unique index on a single field

Use the following procedure in mongosh to build a unique index on the user_id field of the members collection.

db.members.createIndex( { "user_id": 1 }, { unique: true } )

Unique composite index

On a composite index, you can also impose unique constraints. For example, if you use a unique constraint on a composite index, MongoDB enforces uniqueness when combining the index key values.

Use the following operation in mongosh to build a unique index on the groupNumber, lastname, and firstname fields of the members collection.

db.members.createIndex( { groupNumber: 2, lastname: 1, firstname: 1 }, { unique: true } )

The index ensures that every combination of groupNumber, lastname, and firstname values ​​is unique.

Consider the following collection with the following documents.

{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }

Create a unique composite multikey index on a.locand .a.qty

db.collection.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )

The following documents can be included in the collection because the index guarantees the uniqueness of the combination of a.locand values.a.qty

db.collection.insertMany( [
   { _id: 2, a: [ { loc: "A" }, { qty: 6 } ] },
   { _id: 3, a: [ { loc: "A", qty: 12 } ] }
] )

Behavior of unique indexes in MongoDB

limit:

MongoDB will not be able to create a unique index on the provided index field if the collection already contains data that violates the uniqueness requirement of the index. You cannot define unique constraints on hashed indexes.

Creating a unique index using replica sets and sharded clusters

Building unique indexes on replica sets and sharded clusters using rolling operations requires stopping all writes to the collection during the entire process.

If you cannot stop all writes to the collection during this process, do not use a roll operation. Instead, create a unique index for the collection by issuing the following command:

  1. On the primary database of the replica setdb.collection.createIndex()
  2. On mongos of a sharded clusterdb.collection.createIndex()

Unique constraints across separate documents

The unique requirement applies to every document in the collection. A unique index prevents the index key from having the same value in different documents.

Because the restriction applies only to individual documents, a document can have arrays of items that result in duplicate index key values ​​for a unique multikey index, as long as the document's index key values ​​do not duplicate the index key values ​​of another document. In this case, the duplicate index entries enter the index only once.

For example, a collection containing the following documents.

{ _id: 1, a: [ { loc: "A", qty: 6 }, { qty: 10 } ] }
{ _id: 2, a: [ { loc: "A" }, { qty: 7 } ] }
{ _id: 3, a: [ { loc: "A", qty: 12 } ] }

Create a unique composite multikey index on a.loc and a.qty.

db.collection.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )

{"a.loc": "B", "a.qty": null}A unique index allows the following document to be inserted into a collection if there is no other document in the collection with the index key value.

db.collection.insertOne( { _id: 4, a: [ { loc: "B" }, { loc: "B" } ] } )

Unique indexes and missing fields

If a document in a unique index does not contain a value for the indexed field, the index will store a null value for that document. Because of the uniqueness constraint, MongoDB will only allow one document to be missing an indexed column.

If there are multiple documents without a value for the indexed field or the indexed field is missing, index creation will fail with a duplicate key error.

For example, a collection has a unique index on x.

db.collection.createIndex( { "x": 13 }, { unique: true } )

A unique index can insert a document without field x if the collection does not already contain a document missing field x.

db.collection.insertOne( { y: 2 } )

However, if there are already documents in the collection without field x, the unique index will not be able to insert a document without field x.

db.collection.insertOne( { z: 2 } )

The operation cannot insert the document because the unique constraint on the value of field x is violated.

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 12000,
      "errmsg" : "E12000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
   }
})

Unique partial index

Only documents in the collection that match a specific filter expression are indexed in the partial index. Therefore, if you use both a partialFilterExpression and a unique constraint, the unique constraint applies only to documents that match the filter expression.

A partial index with a unique constraint does not prohibit the insertion of documents that do not satisfy the uniqueness constraint if the document does not satisfy the filter requirements.

Sharded Clusters and Unique Indexes

You cannot define a unique constraint on a hash index.

Only the following indexes can be unique in a range sharded collection.

  1. The index value of the shard key.
  2. A composite index with a prefix as the shard key.
  3. The default is _idan index; however, if _idthe field is not the shard key or a shard key prefix, _idthe index only enforces the uniqueness requirement per shard.

A unique index constraint means:

  1. You cannot shard a collection if it has a unique index on another collection to be sharded.
  2. You cannot create a unique index on a collection that is already sharded on other fields.

Sparse and non-sparse unique indexes

Starting in MongoDB 5.0, a single collection can have unique sparse and non-sparse indexes with the same key pattern.

Unique and sparse index creation

In this example, multiple indexes with the same key pattern and different sparse selections are created.

db.scores.createIndex( { score : 2 }, { name: "unique_index", unique: true } )
db.scores.createIndex( { score : 2 }, { name: "unique_sparse_index", unique: true, sparse: true } )

Basic and sparse index creation

You can build simple indexes with the same key pattern both with and without the sparse option.

db.scores.createIndex( { score : 2 }, { name: "sparse_index", sparse: true } )
db.scores.createIndex( { score : 2 }, { name: "basic_index" } )

Duplicate key patterns in basic and unique indexes

With MongoDB 5.0, you may have a base index and a unique index with the same key pattern. Because of the duplication of the key pattern, it is possible to add a unique index to an already indexed field.

example:

Create a basic index with the key pattern { score: 2 } and insert three documents.

db.scores.createIndex( { score : 1 }, { name: "basic_index" } )
db.scores.insert( { score : 1 } )
db.scores.insert( { score : 2 } )
db.scores.insert( { score : 4 } )

{ score: 2 }Create a unique index using the same key pattern .

db.scores.createIndex( { score : 2 }, { name: "unique_index", unique: true } )

An attempt to insert a duplicate score document fails due to the unique index.

db.scores.insert( { score : 4 } )

Validating unique emails using Mongoose

With Mongoose, you can use validation to prevent duplicates in your database. Validation is defined in the Schema type and is a middleware.

You can also create validations in your schema or use Mongooses built-in validations. To prevent duplication, we recommend using the unique attribute as it tells Mongoose that each document should have a unique value for a given path.

It is shorthand for creating a MongoDB unique index on email.

If you're waiting for the index to be built, you can use Mongoose's promise-based events, Model.init()as shown below.

const User = mongoose.model('User', mongoose.Schema({
  email: {
    type: String,
    required: true,
    match: /.+\@.+\..+/,
    unique: true
  }
}));
await User.create([
    { email: 'gmail@google.com' },
    { email: 'bill@microsoft.com' },
    { email: 'test@gmail.com' }
]);

await User.init();
try {
  await User.create({ email: 'gmail@google.com' });
} catch(error) {
  error.message; // 'E12000 duplicate key error...'
}

In this article, unique index in MongoDB will be discussed in detail. Also, finally, the verification of unique email is done in mongoose of MongoDB.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Date comparison in MongoDB

Publish Date:2025/04/28 Views:169 Category:MongoDB

This MongoDB tutorial discusses the issue of returning Date-based queries. In addition, there is also a good tutorial on how to use Date Range queries in MongoDB. Using date ranges in MongoDB We will learn to write MongoDB date range querie

Find objects between two dates in MongoDB

Publish Date:2025/04/28 Views:94 Category:MongoDB

In this article, the problem of finding objects between two dates was briefly discussed. In addition, the operators $gte, $lte, $gt, and $lt used for this purpose were briefly explained in detail. Querying date ranges in MongoDB This sectio

Comparing Dates in MongoDB

Publish Date:2025/04/28 Views:115 Category:MongoDB

Date is a common field in most databases, and sometimes we need to find exact documents from a collection in MongoDB. For example, if we have a collection of orders, we might search for those documents before or after a specific date. In th

Convert string to date in MongoDB

Publish Date:2025/04/28 Views:162 Category:MongoDB

MongoDB is an excellent platform that is growing in popularity. Among the various features it offers, MongoDB also allows you to convert data from one type to another. This may seem like a complex function, but it is very simple to execute.

Building the MongoDB REST API

Publish Date:2025/04/28 Views:70 Category:MongoDB

MongoDB is a flexible and scalable document-oriented database system that is widely used for large-volume data storage. It uses documents and collections instead of the traditional rational database approach of using tables and rows. MongoD

Using ORM with MongoDB

Publish Date:2025/04/28 Views:117 Category:MongoDB

MongoDB introduces a NoSQL solution for data storage and management, consisting of documents represented in JSON style. Like other database systems, MongoDB can also use ORM. In this article, we will explain the concepts of ORM and general

Locking mechanism in MongoDB

Publish Date:2025/04/28 Views:95 Category:MongoDB

In database management systems, locking mechanisms ensure the consistency of the entire result. For example, if some writing process is in progress on the data, a read command cannot be executed at the same time. Database resources are lock

Composite Indexes in MongoDB

Publish Date:2025/04/28 Views:151 Category:MongoDB

Sometimes we need to create an index that contains multiple fields. For example, if your document contains a field called Sex, it may contain two other fields, such as Male and Female. These fields may have values ​​like Yes or No. In t

$unset operator in MongoDB

Publish Date:2025/04/27 Views:78 Category:MongoDB

This article will discuss how the $unset operator works in MongoDB. Additionally, we will demonstrate the use of this operator to remove a field from all documents in a MongoDB collection. $unset operator in MongoDB $unset is an operator us

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial