Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
MongoDB transaction & indexes for duplicate values
To prevent duplicate values within array fields in MongoDB, use createIndex() with the unique option. When a unique index is applied to an array field, MongoDB treats each array element as a separate index entry, preventing any value from appearing in multiple documents.
Syntax
db.collection.createIndex(
{ "arrayField": 1 },
{ "unique": true }
);
Sample Data
Let us create a collection with documents ?
db.demo298.insertMany([
{ Name: "Chris", Marks: [46, 79] },
{ Name: "David", Marks: [67, 88] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4d56e55d93261e4bc9ea48"),
ObjectId("5e4d56f55d93261e4bc9ea49")
]
}
Create Unique Index
Now create a unique index on the Marks array field ?
db.demo298.createIndex({ Marks: 1 }, { unique: true });
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Test Duplicate Prevention
Try to insert a document with a duplicate value (88) that already exists in David's Marks array ?
db.demo298.insertOne({ Name: "Mike", Marks: [88, 98] });
{
"writeError": {
"code": 11000,
"errmsg": "E11000 duplicate key error collection: test.demo298 index: Marks_1 dup key: { : 88.0 }"
}
}
Verify Final Data
Display all documents to confirm only unique array values exist ?
db.demo298.find();
{ "_id": ObjectId("5e4d56e55d93261e4bc9ea48"), "Name": "Chris", "Marks": [46, 79] }
{ "_id": ObjectId("5e4d56f55d93261e4bc9ea49"), "Name": "David", "Marks": [67, 88] }
Conclusion
A unique index on an array field ensures each array element is unique across all documents. MongoDB prevents insertion of documents containing duplicate values, maintaining data integrity through the E11000 duplicate key error.
