7

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?

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know if their are any performance benefits to either approach? Or, if one structure is more common than the other?
The usage of either structure depends on the kind of operations you are going to perform.For example- when you are inserting data in first approach you will be setting boolean values for each of the fields where as in second approach arrays gives you flexibility to insert only the required fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.