4

I have an object like so:

{
    "field1": "somestring",
    "field2": {
        "nestedfield1": "somestring",
        "nestedfield2": "somestring"
    }
}

i can create an index on field1 like so db.collection.createIndex('field1') and it will work as expected. But what if I want an index on both nested fields.

Do I have to do db.collection.createIndex('field2.nestedfield1') to create that index or will db.collection.createIndex('field2') automatically create that?

I will be searching using 'field2.nestedfield1' in my queries and want an index for that.

Thanks

1 Answer 1

1

You can't index nested field at once, you have to index each item inside separately.

To create an index on the nested field, just give its full field path with . separator,

db.collection.createIndex('field2.nestedfield1')
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to create index at field2 and query using {field2: {"nestedfield1": "sth", "nestedfield2": "sth"}}?

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.