MongoDB – How to Create Multiple Indexes on Same Field

mongodb

For example, I created this index:

db.test.createIndex({field1:1}, {partialFilterExpression:{field2:{$gt:10}}})

Index created successfully. Then I want to create second index:

db.test.createIndex({field1:1}, {partialFilterExpression:{field2:{$lte:10}}}

But above will give error IndexOptionsConflict, but no error details, only dumps the index object.

I have tested to create such indexes on PostgreSQL and it works. How can I do this in MongoDB?

Best Answer

Sadly, a restriction of MongoDB:

Restrictions

In MongoDB, you cannot create multiple versions of an index that differ only in the options. As such, you cannot create multiple partial indexes that differ only by the filter expression.

Right now, you can only do this:

db.test.createIndex({field1:1}, {partialFilterExpression:{field2:{$gt:10,$lte:10}}})

Or use composite indexes with a placeholder field:

db.test.createIndex({field1:1, never_use_this_field1: 1}, {partialFilterExpression:{field2:{$gt:10}}})
db.test.createIndex({field1:1, never_use_this_field2: 1}, {partialFilterExpression:{field2:{$lte:10}}}