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

喜你入骨 提交于 2019-12-10 21:21:26

问题


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


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/13473987/how-to-accumulate-results-with-foreach-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!