这是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" } } );
为什么文件的顺序很重要?
答案 0 :(得分:2)
因为在JSON和BSON中,字段的顺序在序列化时有所不同。即。
{ city: "New York", state: "NY" }
与
不同{ state: "NY" , city: "New York" }
实际索引的值在第一种情况下为“New YorkNY”,在第二种情况下为“NYNew York”(粗略)。由于在索引中搜索嵌入文档之前没有方法无法规范化字段顺序。
要解决此问题,您可以使用复合索引:
db.factories.ensureIndex( { "metro.city": 1, "metro.state": 1 })
查询(这里的顺序无关紧要):
db.factories.find( { "metro.city": "New York", "metro.state": "NY" } )