最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to accumulate results (with forEach?) in MongoDB? - Stack Overflow

programmeradmin3浏览0评论

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 (sids) into an array instead of just printing them?

Update: ruby-style one-liner is preferred (but not required) of course

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 (sids) into an array instead of just printing them?

Update: ruby-style one-liner is preferred (but not required) of course

Share Improve this question edited Sep 22, 2017 at 18:01 CommunityBot 11 silver badge asked Nov 20, 2012 at 13:13 Alexander AbramovichAlexander Abramovich 11.5k26 gold badges74 silver badges113 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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;})

You can use a variable in the parent scope.

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
});

Push the id's to a array:

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

评论列表(0)

  1. 暂无评论