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:开发者_StackOverflow中文版 { $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.
{ city: "New York", state: "NY" }
is not the same as
{ state: "NY" , city: "New York" }
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:
db.factories.ensureIndex( { "metro.city": 1, "metro.state": 1 })
And query with (here the order doesn't matter):
db.factories.find( { "metro.city": "New York", "metro.state": "NY" } )
精彩评论