2014-02-13 83 views
0

我想使用下面的命令跳過mongo map reduce utility的記錄。Mongo DB Map減少跳過記錄

db.<collectionName>.mapReduce(
"function() { counter++; if (counter > <numberOfRecordsToBeSkipped>){ emit(this.fieldName, 1); } }", 
"function (key, values) { return Array.sum(values); }" , 
{"out" : <CollectionName>,"scope" : "{var counter:0}" , 
"limit" : 0} 
); 

我不斷收到以下錯誤。

uncaught exception: map reduce failed:{ 
    "errmsg" : "exception: map invoke failed: JS Error: ReferenceError: counter is not defined nofile_b:0", 
     "code" : 9014, 
"ok" : 0 
} 

任何人都可以請幫助我嗎?我知道範圍屬性可以用來定義要在地圖/縮小功能中使用的全局變量。

回答

0

雖然你的語法是錯誤的scope參數:

scope: { counter: 0 } 

你也會碰到了scope文件旨在爲只讀的問題。如果傳遞給scope的文檔僅在一個分片服務器上進行更改,則分片設置不起作用。此外,不能保證由map-reduce處理的文檔的順序從執行到執行都是相同的。所以,這會產生不一致的結果。

這裏有一個簡單的測試與具有userid領域的文檔:

{ 
    userid: 1234 
} 

代碼:

map = function() { counter++; if (counter > 1){ emit(this.userid, 1); } } 
reduce = function (key, values) { return Array.sum(values); } 

在使用中:

db.tw.mapReduce(map, reduce, { out: "tw2", scope: { counter: 0 } }) 

的代碼按預期執行。通過將counter預設爲某個值,我控制了在map階段處理了多少個文檔。我確認輸出符合預期。

如果我更改地圖代碼:

map = function() { counter++; if (counter > numberToSkip) { emit(this.userid, 1); } } 

並嘗試調用mapReduce功能沒有任何變化,我會看到有errmsg

ReferenceError: numberToSkip is not defined near 'ounter > numberToSkip){ emit(thi' " 
+0

謝謝。不過,我嘗試了你的建議,但仍然遇到同樣的問題。不知何故,我在範圍內定義的變量不適用於地圖功能。 – user3306944

+0

你有其他錯誤嗎?我可以讓它工作。它甚至不是隻讀的(MongoDB建議他們將範圍變量設置爲只讀)。您的代碼有其他JavaScript錯誤。 – WiredPrairie

+0

此外 - 你使用的是什麼版本的MongoDB?你看到的錯誤與我所看到的不一致有點奇怪。 – WiredPrairie