Mongodb Pymongo create an index for nested object

Viewed 527

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 Answers

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')
Related