Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing Array Items In Mongoose

I have a schema that looks something like ...

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
    }],
    // other properties ...
});

I perform queries of the form Items.find({ sizes: { $elemMatch: 'someSize' } });
So I want to add index to those sizes inside of an element so the query is performed quickly.

Should it be something like:

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
        index: true,
    }],
    // other properties ...
});

or

const itemSchema = new Schema({
    sizes: {
        type: [{
            type: String,
            enum: [/* some fixed sizes */],
        }],
        index: true,
    },
    // other properties ...
});

or maybe a third option ?

like image 848
Amr Saber Avatar asked Sep 04 '26 02:09

Amr Saber


1 Answers

I discovered that what I wanted is called Multikey Indexing and found its docs on MongoDB.

According to that, indexing a field whose type is an array will create an index for each field of the array all pointing to the same document, which is exactly what I wanted to optimize my queries.

So the right answer would be

const itemSchema = new Schema({
    sizes: {
        type: [{
            type: String,
            enum: [/* some fixed sizes */],
        }],
        index: true,
    },
    // other properties ...
});

but on experimenting and checking collection indexes (with compass), I found that this

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
        index: true,
    }],
    // other properties ...
});

will also work in the same manner and will create an index on sizes field which will be a multikey index.

So pretty much the 2 forms are acceptable, and are working as expected; I prefer the one that explicitly indexes the sizes field though.

like image 111
Amr Saber Avatar answered Sep 06 '26 15:09

Amr Saber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!