2011-06-14 52 views
0

這是MongoDB docsMongoDB ::爲什麼嵌入式文檔索引不要以相反的順序返回文檔?

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" } }); 

爲什麼顯著文件的順序?

回答

2

因爲在JSON和BSON中,序列化時字段的順序會有所不同。即

{ city: "New York", state: "NY" } 

是不一樣的

{ state: "NY" , city: "New York" } 

實際上索引將是「新YorkNY」在第一種情況和「NYNew紐約」在第二種情況下(大約)的值。由於在索引中搜索嵌入文檔之前沒有方案無法對字段順序進行規範化。

爲了克服這一點,你可以使用複合指數:

db.factories.ensureIndex({ "metro.city": 1, "metro.state": 1 }) 

和查詢與(這裏的順序並不重要):

db.factories.find({ "metro.city": "New York", "metro.state": "NY" }) 
+0

來源爲「由於JSON和BSON的順序領域有所作爲「? – CamelCamelCamel 2011-06-25 16:45:18

+0

@Radagaisus這是一個糟糕的聲明。我的意思是在這方面有所不同(序列化和索引)。 BSON或JSON本身不強制執行任何次序,而且對象比較語義由實現決定。 – pingw33n 2011-07-01 17:43:32

+0

「由於在索引中搜索嵌入文檔之前沒有任何方法無法正常化字段順序」......只是一個想法:如何按字母順序(字段名稱)對字段進行排序? – 2011-07-01 17:52:23