I'm having some issues creating multiple compound indexes on one of my schemas in MongoDB. When using MongoLab, I know some indexes are not created when they are too long, due to a naming issue. So I suspect this might be the reason why some are not created
var Schema = new mongoose.Schema({ ... });
// Created
Schema.index({
one: 1,
three: 1
});
// Not Created
Schema.index({
one: 1,
two: 1,
three: 1,
four: 1,
five: 1,
six: 1,
seven: 1,
eight: 1,
nine: 1,
ten: 1
});
To create a compound index use an operation that resembles the following prototype: db. collection. createIndex( { <field1>: <type>, <field2>: <type2>, ... } )
Or in other words, compound indexes are those indexes where a single index field contains references to multiple fields. In MongoDB, the compound index can contain a single hashed index field, if a field contains more than one hashed index field then MongoDB will give an error.
Generally, MongoDB only uses one index to fulfill most queries. However, each clause of an $or query may use a different index, and in addition, MongoDB can use an intersection of multiple indexes. The following documents introduce indexing strategies: Use the ESR (Equality, Sort, Range) Rule.
MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query.
There is a limitation to the default index name (https://docs.mongodb.org/manual/reference/limits/#Index-Name-Length)
You can specify custom index name by passing addition option object to Schema.index
Schema.index({
one: 1,
two: 1,
three: 1,
four: 1,
five: 1,
six: 1,
seven: 1,
eight: 1,
nine: 1,
ten: 1 },
{ name: 'my_index_name' }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With