How to Create a nested index in MongoDB?

MongodbIndexing

Mongodb Problem Overview


A. How do I index nested and all of it's values?

B. How do I index valuetwo?

{
    id: 00000,
    attrs: {
        nested:{
            value: value1,
            valuetwo: value2,
        }
    }
}

I've looked here: http://www.mongodb.org/display/DOCS/Indexes, and the docs to my knowledge, aren't clear about indexing things that aren't nested.

Mongodb Solutions


Solution 1 - Mongodb

You'd create them just as if you were creating an index on a top level field:

db.collection.createIndex({"attrs.nested.value": 1})

You do need to explicitly create indexes on each field.

Solution 2 - Mongodb

MongoDB automatically creates a multikey index if any indexed field is an array; you do not need to explicitly specify the multikey type.

This will work for both the scenario's

db.coll.createIndex( { "addr.pin": 1 } )

Scenario 1 nested OBJECTS

{
  userid: "1234",
  addr: {
	pin:"455522"
  }
},
{
  userid: "1234",
  addr: {
	pin:"777777"
  }
}

Scenario 2 nested Arrays

{
  userid: "1234",
  addr: [
    { pin:"455522" },
    { pin:"777777" },
  ]
}

https://docs.mongodb.com/manual/core/index-multikey/

Solution 3 - Mongodb

A. to index all the properties in "nested" you will have to index them separately:

db.collection.createIndex({"attrs.nested.value": 1});
db.collection.createIndex({"attrs.nested.valuetwo": 1});

This can be done in one command with:

db.collection.createIndexes([{"attrs.nested.value": 1}, {"attrs.nested.valuetwo": 1}]);

B. to index just "valuetwo":

db.collection.createIndex({"attrs.nested.valuetwo": 1})

Use createIndex over ensureIndex as ensureIndex is Deprecated since version 3.0.0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr. Demetrius MichaelView Question on Stackoverflow
Solution 1 - MongodbBryan MigliorisiView Answer on Stackoverflow
Solution 2 - MongodbArun Pratap SinghView Answer on Stackoverflow
Solution 3 - MongodbcianmceView Answer on Stackoverflow