How to accumulate results (with forEach?) in MongoDB?

javascript, mongodb, mongodb-query, nosql

Solution

Call `toArray` on the cursor instead of `forEach`:

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

UPDATE

Seems you can skip the `toArray` and go right to the `map` as the cursor provides that method directly:

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

Problem

Suppose I want to search through a collection, scan the returned result set and return some transformation of it. I've tried the following code: ``` db.my_collection.find({timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20).forEach(function(element) { print(element.sid); }) ``` Ok, it worked well. To the question: how can I accumulate the results (`sid`s) into an array instead of just printing them? Update: ruby-style one-liner is preferred (but not required) of course

Original source