2013-12-23 76 views
1

我正在嘗試爲常用查詢創建複合索引。使用Mongo複合索引

有兩個字段。一個String類型的'client'字段,包含一個IP地址。另一個是類型爲Date的'sendOn'字段。我正在查找客戶端爲空且sendOn位於特定範圍之間的文檔。

支持上升的山頓字段排序中,我建立了我需要的1

所以值的山頓指標,我已經運行

> db.queries.ensureIndex({"client":1,"sendOn":1}) 

> db.queries.find({ $query: { client: { $exists: false } , sendOn: { $gt: new Date(1387664033883), $lt: new Date(1387750493883) } } }).explain() 

{ 
     "cursor" : "BasicCursor", 
     "nscanned" : 2546133, 
     "nscannedObjects" : 2546133, 
     "n" : 0, 
     "millis" : 25071, 
     "nYields" : 0, 
     "nChunkSkips" : 0, 
     "isMultiKey" : false, 
     "indexOnly" : false, 
     "indexBounds" : { 

     } 
} 

文檔說$ exists查詢通常效率低下。我考慮過迫使文檔至少包含一個空的客戶端字段。但是那個查詢不使用索引呢?

回答

1

它應該使用索引(假定您用空值替換$ exists,如您所述 - $ exists操作符未針對索引進行優化)。

你可能會在某個時候在這裏搞亂事情:文檔指出你不應該使用.explain()以$查詢格式:

http://docs.mongodb.org/manual/reference/operator/meta/query/

試試這個:

db.queries.find({ $query: { client: null , sendOn: { $gt: new Date(1387664033883), $lt: new Date(1387750493883) } }, $explain: true }); 
+0

感謝您的快捷方式。有熟悉的事情真好。 – EthernetCable