So now before we have a look at other index types mongdb supports,
let's see how we can configure the index types we already know
and for that, let's again have a look at one person in our contacts data and let's create our own unique
index.
The ID index which you get out of the box for this field actually is unique by default
too, this is a setting mongodb gives you
and this ensures that you can't add another document with the same value into the same collection.
Now sometimes you have the use case
that you also need that behavior for a different field and therefore you can add your own unique indexes.
Let's say for e-mail but of course we could have used login uuid if we wanted to but let's use
that top level email element here
and let's create an index on contacts with create index of course,
on email let's say in ascending order and here, I now pass a second argument to create index where I
configure this index, there
I can now set unique to true. If I hit enter,
I get an error that we have some duplicate keys as it seems,
so this generally worked
but it found a duplicate key here for Abigail Clark.
Now let's quickly confirm this by looking into contacts and finding all contacts where the e-mail is
this value here,
Abigail Clark without that backslash.
If I hit enter or I simply count that, I see I have two persons with that indeed
and this is already one advantage of the unique index,
we get such a warning if we want to add it or if we already had it in place and we tried to add a document
with a value that already existed, we would have gotten an error during that insert operation.
So unique indexes can help you as a developer
ensure data consistency and help you avoid duplicate data for fields that you need to have unique,
so the id, _id is unique by default but you have other use cases like maybe that email here
too
and the unique index is a great way for you to not just speed up your find queries but also to guarantee
that you have unique values for that given field in that collection.