2014-11-24 105 views
2

在我的用例中,我有超過3000個變量ids,我已經將其分配給其他集合作爲mongo db中的外鍵。在其他集合中,對於每個外鍵,包含列表類型中的一個字段的文檔數量更多。我需要通過滿足至少一個每個外鍵列表大小的文檔大於0的條件來查詢從3000中檢索不同的外鍵。我目前使用下面的查詢作爲示例。Mongo Db優化查詢

db.values.distinct('variable',{variable:{$in:variableIds}, $nor:[{source: {$exists: false}},{source: {$size: 0}}]})

其中變量如下面的 「值」 收藏的外鍵。 variableIds是作爲變量集合的主鍵的唯一標識列表。

{ 
"_id" : ObjectId("546db048e4b0c0187ab9eefd"), 
"dateNum" : 41274, 
"source" : [ 
    { 
     "value" : 625, 
     "formatCode" : "General" 
    } 
], 
"variable" : ObjectId("546db048e4b0c0187ab9eefc") 
} 

但由於$in條件3000個IDS查詢似乎是大花更多的時間來執行有另一種方式來優化查詢?

回答

2

一個優化是將variable字段添加到index

只是爲了證明其效果。讓值是一個只有三個文檔的集合,其中兩個匹配我們正在尋找的variable

的樣本數據:

db.values.insert([{ 
"_id" : 1, 
"dateNum" : 41274, 
"source" : [ 
    { 
     "value" : 625, 
     "formatCode" : "General" 
    } 
], 
"variable" : 1 
}, 
{ 
"_id" : 2, 
"dateNum" : 41274, 
"source" : [ 
    { 
     "value" : 625, 
     "formatCode" : "General" 
    } 
], 
"variable" : 1 
}, 
{ 
"_id" : 3, 
"dateNum" : 41274, 
"source" : [ 
    { 
     "value" : 625, 
     "formatCode" : "General" 
    } 
], 
"variable" : 2 
} 
]) 

假設我們運行在這個集合的查詢,而無需對變量字段的索引。

db.runCommand({ distinct: 'sample', 
       key:'variable', 
       query:{variable:{$in:[1]}, 
         $nor:[{source: {$exists: false}},{source: {$size: 0}}]} 
       }) 

我們得到下面的輸出。在檢查輸出時,我們發現集合中掃描的文檔總數nscannedObjects的值爲3。所以這導致了完整的收集掃描。

{ 
     "values" : [ 
       1 
     ], 
     "stats" : { 
       "n" : 2, 
       "nscanned" : 3, 
       "nscannedObjects" : 3, 
       "timems" : 0, 
       "cursor" : "BasicCursor" 
     }, 
     "ok" : 1 
} 

現在我們在variable字段中添加一個索引。

db.sample.ensureIndex({"variable":1}) 

而上運行的命令,我們得到以下輸出,指出掃描的總文檔僅2。這些文檔具有與搜索查詢中相同的確切variable

{ 
     "values" : [ 
       1 
     ], 
     "stats" : { 
       "n" : 2, 
       "nscanned" : 2, 
       "nscannedObjects" : 2, 
       "timems" : 59, 
       "cursor" : "BtreeCursor variable_1" 
     }, 
     "ok" : 1 
} 
+0

我已經添加了指數也顯示了同樣的結果,我也搜索在$傳球超過3000個項目中會造成任何性能問題,也沒有任何其他替代查詢除了使用不同 – 2014-11-24 08:59:39

+1

指數領域'variable'和'source.value'。然後嘗試下面的查詢:db.sample.distinct('variable',{variable:{$ in:[1]},「source.value」:{$ exists:true}}) – BatScream 2014-11-24 09:11:22