How it works...
In step 1 we inserted a document in a new collection testuniq. Next, in step 2, we created an index on the field foo with the parameter {unique: true}. In step 3, we try to add another record with the same value of field foo as we did earlier and we receive an error as expected.
In step 4, we drop the indexes and add a duplicate record. Next we try to create a new unique index. This time we are not allowed because there are duplicates in our collection.
This is a simple example of how to create an index with unique constraint. Additionally, we can also create unique indexes on fields that have an array, for example {foo: ['bar', 'baz']}. MongoDB would inspect each value of the array and against the index. Try adding a document ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access