The advantage of a unique index in MongoDB

I tried searching the Mongo documentation, but I can’t find any details on whether queries on unique indexes will be faster than queries on non-ideal indexes (given the same data)

Therefore, I understand that a unique index will have high selectivity and good performance. But, given two fields whose concatenation is unique, will a non-specific composite index work slower than a unique composite index?

I suggest that unique indexes can slow down inserts as uniqueness needs to be verified. But is a read performance improvement a unique index, if any, really worth it?

+8
mongodb mongodb-indexes unique-index
source share
3 answers

The quick grep of the source tree seems to indicate that unique indexes are used only for insertion, so there should be no performance or damage benefits between a query that returns a single document, regardless of whether the index is unique or not.

MongoDB indices are implemented as btrees, so it makes no logical sense for them to perform differently, regardless of whether the index is unique or not.

+13
source share

I did a little research on this topic. I created 500,000 records (randomly generated strings) in the collection and tried a couple of queries with explain (). db.test.find () with no indexes

Then I provided a unique index and tried several other queries again: db.test.find () with unique index

As you can see, after adding the index, the time consumption decreased from ~ 276 ms to 0 ms! So, even if the index is unique, it affects (positively) the search for queries.

+1
source share

A unique index or unique constraint works exactly the same as with an RDBMS. Uniqueness is checked during input, but has nothing to do with read performance (why?). Why are you asking this question? Are there any rational reasons for this question? Have you done any performance tests? Do you have a problem with the real world? Use a unique index if you need one point. Any further discussion is probably pointless.

-6
source share

All Articles