Create an index on the non-used field for the cars collection. mongodb NoSql

Viewed 24

I have a field that uses boolean values for the used cars. how can I index used: false?

db.cars.createIndex({ model: 1, used:-1 })

would this be correct syntax to show non used cars?

1 Answers

It actually depends on the queries you perform and the distribution of boolean values of the used field. Generally speaking, if you usually query both fields like this :

db.cars.find({ model: ..., used: false });

This index would do the job. It does not matter if you index used: -1 or used: 1 since sort does not really apply here.

db.cars.createIndex({ model: 1, used: 1 })

But bear in mind that if your boolean values distribution is equal, i.e. 50% true and 50% false, the index over a boolean field will not boost your query. However, if you primarily look for used: false and most of your documents in the DB have this field as false, then the index will improve your query time.

Related