@rollin
In MongoDB, a composite unique key is a key that enforces uniqueness on a combination of multiple fields in a document. To create a composite unique key in MongoDB, you can use the createIndex()
method along with the unique
option set to true
. Here's how you can create a composite unique key in MongoDB:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'myDatabase'; MongoClient.connect(url, function(err, client) { const db = client.db(dbName); // Create a composite unique index on multiple fields db.collection('myCollection').createIndex({ field1: 1, field2: 1 }, { unique: true }, function(err, result) { if (err) { console.log(err); } else { console.log('Composite unique key created successfully'); } client.close(); }); }); |
In the code above, replace field1
and field2
with the names of the fields on which you want to enforce uniqueness. The createIndex()
method is called on the myCollection
collection with an object containing the fields and the unique
option set to true
. This will create a composite unique key on the combination of field1
and field2
.
Once the index is created, MongoDB will prevent documents with duplicate combinations of field1
and field2
values from being inserted into the collection.