Mongodb – Use index intersection feature in MongoDB 2.6 as compound shard key

indexmongodbsharding

I have three indexes on name, age, salary.

I can use them as compound index on MongoDB 2.6 (name and age together), but can I use the same indexes as compound shard key?

I also have a constraint that this will be a unique shard key.

Will it work?

Best Answer

In order to deploy a shard key in your case (name, age) you need to pre-create an index on (name, age).

The shard key can be unique, but I don't see how a unique constraint fits here, for example isn't it quite likely to have two same records? (name:Mary age:26?).

You cannot enforce a unique constraint directly to the database without a compound index.

Index intersection is to combine two index on the run-time. For example, you have an index on name and one on age and a query {name='somename' and age='someage'}. Prior to 2.6, you needed a compound index on (name, age). On 2.6, the optimizer can use these individual indexes to execute the above query.