George Hess
George Hess

Reputation: 689

MongoDB index: object keys vs array of strings

I'm new to the MongoDB and have been researching schema designs and indexing. I know you can index a property regardless of its value (ID, array, subdocument, etc...) but what I don't know is if there is a performance benefit to either indexing an array of strings or a nested object's keys.

Here's an example of both scenarios that I'm contemplating (in Mongoose):

// schema
mongoose.Schema({
    visibility: {
        usa: Boolean,
        europe: Boolean,
        other: Boolean
    }
});
// query
Model.find({"visibility.usa": true});

OR

// schema
mongoose.Schema({
    visibility: [String] // strings could be "usa", "europe", and/or "other"
});
// query
Model.find({visibility: "usa"});

Documents could have one, two, or all three visibility options.

Furthermore, if I went with the Boolean object design, could I simple index the visibility field or would I need to put an index on usa, europe, and other?

Upvotes: 7

Views: 5620

Answers (1)

Avi
Avi

Reputation: 296

In MongoDB creating indexes on an array of strings results into multiKey index where all the strings in the array form the index keys and point to the same document.So in your case it would work same as nested object keys.

If you go with boolean design and you can put index on visibility field.You can further read on MongoDB Mulitkey indexing

Upvotes: 7

Related Questions