2012-11-20 17 views
3

假設我想搜索一個集合,掃描返回的結果集並返回它的一些變換。我試了下面的代碼:如何在MongoDB中累積結果(with forach?)?

db.my_collection.find({timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20).forEach(function(element) { print(element.sid); }) 

好吧,它運行良好。對於這個問題:如何將結果(sid s)累加到數組中而不是僅僅打印它們?

更新:紅寶石式的單行當然

回答

4

呼叫toArray上的光標,而不是forEach

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20) 
    .toArray().map(function(o){return o.sid;}) 

UPDATE

似乎可以跳過toArray和向右走的map當光標直接提供的方法:

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20) 
    .map(function(o){return o.sid;}) 
+0

調用'指定者()'將返回對象的數組,比如'{SID: 「1234」}'。我想讓他們沒有'sid',只是號碼 – BreakPhreak

+0

@BreakPhreak好的,我更新了答案。 – JohnnyHK

+0

你可以鏈接到'地圖()'功能嗎? (無論如何接受) – BreakPhreak

0

的首選(但不要求)您可以在父範圍內使用的變量。

var myArr = []; //the results will go there 
db.my_collection.find({timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20).forEach(function(element) { 
    myArr.push(element.sid); //this function has access to myArr 
}); 
0

推ID的一個數組:

var myArray = []; 
b.my_collection.find({timestamp : {$gt: 1343032491799}}, {_id:0,sid:1 }) 
    .limit(20) 
    .forEach(function(element) { 
     myArray.push(element.sid); 
    })​