6

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
});
woutr_be
  • 9,532
  • 24
  • 79
  • 129
  • does it print some thing to the screen when create 2nd index ? how do you know that the second index is not created ?Did you check in mongo shell ? – somallg Feb 03 '16 at 02:28
  • @somallg I didn't add any logging yet. I did check the mongo shell and it wasn't created, hence how I know. When I manually try to create that index, i get the following: "The default index name generated by MongoDB is too long. Please specify a custom name." – woutr_be Feb 03 '16 at 02:38
  • 1
    Your right, there is a limitation to the default index name (https://docs.mongodb.org/manual/reference/limits/#Index-Name-Length) You can specify custom name by passing addition option 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' } );` – somallg Feb 03 '16 at 02:49
  • Thanks, that was exactly what I was looking for – woutr_be Feb 03 '16 at 03:56
  • @somallg Can you add that as an answer, then I can mark it as solved – woutr_be Feb 03 '16 at 03:56

1 Answers1

8

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' }
);
somallg
  • 1,923
  • 13
  • 12
  • [“By default, **`` is the concatenation of the field names and index type.** You can explicitly specify the `` to the `createIndex()` method to ensure that the fully qualified index name does not exceed the limit.” “**Fully qualified index names,** which includes the namespace and the dot separators (i.e. `..$`), **cannot be longer than 128 characters.**”](https://docs.mongodb.org/manual/reference/limits/#Index-Name-Length) – Константин Ван Feb 08 '18 at 17:59