2013-08-25 26 views
0

假設我有一些字段爲'State'的文檔,我需要在下一個文檔中檢測它的更改。對於這一點,我想比較當前光標next()用MongoDB檢測收集字段與.next()時發生變化

cursor.forEach(
     function(thisCursor){ 
      print('Current: '+thisCursor.State); 
      print('Next: '+cursor.next().State); 
     } 
) 

但輸出是這樣的:

Current: Florida 
Next: Florida 
Current: New Mexico 
Next: New Mexico 

所以很明顯.next()是不工作的。有關爲什麼發生這種情況的任何想法

感謝

+0

您使用的是什麼平臺/編程語言? – WiredPrairie

+0

只需mongoDB javascript命令行 – Joss

回答

2

雖然你可以使用forEach通過收集迭代,你最終會跳過所有其他指數。

遊標只是結果集中的一個位置。 forEach通常會將當前移動到下一個項目,但通過在光標實例上手動調用next,您可能會無意中跳過該集合。

> db.states.remove() 
> db.states.insert({name: "alabama"}) 
> db.states.insert({name: "alaska"}) 
> db.states.insert({name: "arkansas"}) 
> db.states.insert({name: "wisconsin"}) 
> db.states.insert({name: "west virginia"}) 

然後,初始化光標:

> var cursor=db.states.find(); 

如果我使用forEachnext

> cursor.forEach(function(item){ 
    print("name: " + item.name); 
    print("next name: " + cursor.next().name); }) 

它導致:

name: alabama 
next name: alaska 
name: arkansas 
next name: wisconsin 
name: west virginia 
Sun Aug 25 15:04:12.197 error hasNext: false at src/mongo/shell/query.js:124 

正如你所看到的,詛咒或者在整個集合中移動,然後,因爲hasNext未被使用,所以它將步驟超出集合的長度。

您需要更改邏輯以實際讀取「下一個」文檔,而不會影響以下forEach循環迭代。

雖然我不明白你的數據的性質,你也許能夠做這樣的事情:

> var doc=cursor.hasNext() ? cursor.next() : null; 
> while(doc) { 
     var currentDoc=cursor.hasNext() ? cursor.next() : null; 
     if(currentDoc && currentDoc.name === doc.name) { 
      print("matched: " + currentDoc.name); 
     } 
     doc = currentDoc;    
    } 

它獲取一個文檔,然後獲取下一個文件,如果有一個,並確定它到第一個。然後,通過將以前的文檔與當前文檔進行比較來重複。循環直到沒有更多文檔。

如果您的邏輯變得更復雜,我強烈建議您嘗試使用Node.JS和本地MongoDB驅動程序。

此外,如果您的結果超過20個,則可能需要將批量大小設置爲較大的數字。見here

相關問題