ic3
ic3

Reputation: 7680

MongoDB performance - distinct with query on two fields with Index

We've a collection with two fields ( A and B ), both have an index.

Getting the disctinct on any of them is amazingly quick. But the actual query is a disctinct in A with a filter on the other field, B.

db.getCollection('Collection').distinct( "A" , { "B" : "b1" }  )

This is really, really slow as it's scanning the collection ( unfortunatly b1 is not filtering more than a 50% ). Is there a way to make this quicker in MongoDB ?

Upvotes: 1

Views: 451

Answers (2)

Mohammad Taherian
Mohammad Taherian

Reputation: 1694

I recommend you to use compound index to solve this problem. As priority is important in compound index based on you query, I recommend you to use this index {A:1, B:1}

Upvotes: 1

dnickless
dnickless

Reputation: 10918

According to this JIRA ticket what you can do is just create a composite index like this:

db.collection.createIndex({ "B": 1, "A:" 1 })

Upvotes: 1

Related Questions