This is from MongoDB docs:
db.factories.insert( { name: "xyz", metro: { city: "New York", state: "NY" } } );
db.factories.ensureIndex( { metro : 1 } );
// this query can use the above index:
db.factories.find( { metro: { city: "New York", state: "NY" } } );
//As well as this
db.factories.find( { metro: { $gte : { city: "New York" } } } );
// But this query will not return the document because the order of the fields is significant and doesn't match in this case
db.factories.find( { metro: { state: "NY" , city: "New York" } } );
Why is the order of the documents significant?
Because in JSON and BSON the order of fields makes difference when serialized. I.e.
is not the same as
The value actually indexed will be “New YorkNY” in the first case and “NYNew York” in the second case (roughly). Since there’s no scheme no way to normalize field order prior searching the embedded document in the index.
To overcome this you can use compound index:
And query with (here the order doesn’t matter):