Organizational Research By

Surprising Reserch Topic

advantage of a unique index in mongodb

advantage of a unique index in mongodb  using -'mongodb,unique-index,mongodb-indexes'

I've tried to search through Mongo documentation, but can't really find any details on whether queries on unique indexes will be faster than queries on non-unique indexes (given the same data)

So I understand that a unique index will have high selectivity and good performance. But, given two fields whose concatenation is unique, would a non-unique compound index perform slower than a unique compound index?

I am assuming that unique indexes can slow down inserts as the uniqueness must be verified. But is the read performance improvement of a unique index, if any, really worth it?

asked Oct 13, 2015 by mca.agarwal
0 votes
1 view

Related Hot Questions

3 Answers

0 votes

A quick grep of the source tree seems to indicate that unique indexes are only used on insert, so there shouldn't be any performance benefit or detriment between a query that returns one document, whether the index is unique or not.

MongoDB indexes are implemented as btrees, so it wouldn't make any logical sense for them to perform any differently whether the index is unique or not.

answered Oct 13, 2015 by nimisha.jagtap
0 votes

A unique index or unique constraint works exactly the same way as with a RDBMS. Uniqueness is checked at insertion time but has nothing to do with read performance (why should it?). Why do you ask this question? Are there any rational reasons behind this question? Have you done any performance benchmarks? Do you have any real world problems? Use a unique index when you need one - point. Every further discussion is likely pointless.

answered Oct 13, 2015 by amit.gupta
0 votes

I did my own small research on that topic. I generated 500,000 records (randomly generated strings) in a collection, and tried a couple of queries with explain() statement. db.test.find() with no indexes

Then I ensured a unique index, and tried few other queries again: db.test.find() with unique index

As you can see, after adding index the time consumption decreased from ~276ms to 0ms! So it seems like even if the index is unique, it affects (in a positive way) the find queries.

answered Oct 13, 2015 by abhimca2006