How to Prevent Creating Duplicate Keys in MongoDB
- By : Mydatahack
- Category : DBA, Infrastructure
- Tags: Index, Mongo Shell, MongoDB, Node.js, Unique Index
In MongoDB, the primary key is reserved for the _id field. This is a system field and gets created by default when inserting new records. When you want to enforce the uniqueness in other fields, you can use unique index.
Here is how to create unique index with Mongo Shell. Unique key can be a compound key. You can use getIndexes() to get indexes on the collection.
db.students.createIndex( { "studentId": 1 }, { unique: true } )
# (2) Compound
db.students.createIndex(
{ "studentId": 1, lastname: 1, firstname: 1 },
{ unique: true } )
# (3) Get indexes
db.students.getIndexes()
Now, let’s check out how it can be done with Node.js. In Node, you can use createIndex() as in the Mongo shell. As usual, it is asynchronous and you need a callback function with the usual error-first signature.
When you first run the code, it inserts the records and create unique index on the studentId field. When you run it for the second time and try to insert the same records, you will get an error on insertion because it is violating the unique index rule.
// Setting up const MongoClient = require('mongodb').MongoClient const url = 'mongodb://yourUsername:yourPassword@localhost:27017/admin' // Data const initialData = [{ studentId:1, firstName:'John', lastName:'West', Major:'Psychology' },{ studentId:2, firstName:'John', lastName:'Doe', Major:'Science' },{ studentId:3, firstName:'Shane', lastName:'West', Major:'IT' }] // function to create uniqe index const uniqueIndex = (collection, callback) => { collection.createIndex({studentId:1}, {unique:true}, (err, result) => { if(err) {console.error(`Failed to create index ${err}`); process.exit(1);} console.log(`Unique Index created successfully: ${result}`) callback(result) }) } // function to insert student records const insertStudents= (collection, callback) => { collection.insert(initialData, (err, result) => { if (err) { console.error(`Error in insertion: ${err}`) process.exit(1) } console.log(`No of records (result.result.n): ${result.result.n}`) console.log(`No of records (result.ops.length): ${result.ops.length}`) callback(result) }) } // put them all together MongoClient.connect(url, (err, client) => { if (err) return process.exit(1) console.log('Connection successful.') const db = client.db('usermanaged') const collection = db.collection('students') insertStudents(collection, () => { uniqueIndex(collection, () => { client.close() console.log('Connection closed') }) }) })
REFERENCE