Jacky Wang
Jacky Wang

Reputation: 3520

How to create a compound index in MongoDB

Recently I have created a collection that contains a limited number (<5 by now) of kind of data, I created the collection with entity_type and entity_id, as following shown

+-------------+-----------+---------+------
| entity_type | entity_id | date    | ...
+-------------+-----------+---------+------

And since the query for the latest records are more frequency. So I created the following compound index (note that the entity_id is not globally unique)

[('date': -1), ('entity_type': 1), ('entity_id': 1)]

However, I am not sure if such index is okay since someone said that the index should not created on a field (here it is entity_type) which only has limited values.

Upvotes: 1

Views: 53

Answers (1)

Sandesh
Sandesh

Reputation: 1044

It's recommended to create mongodb index on fields which ensures high selectivity.

So if entity_type column contains limited values, I would suggest to remove this column from compound index.

MongoDB Index Selectivity

Upvotes: 1

Related Questions