如何在MongoDB中累积结果(使用forEach?)? [英] How to accumulate results (with forEach?) in MongoDB?
本文介绍了如何在MongoDB中累积结果(使用forEach?)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我要搜索一个集合,扫描返回的结果集并对其进行一些转换.我尝试了以下代码:
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); })
好的,效果很好.问题是:如何将结果(sid
s)累积到一个数组中,而不是仅仅打印它们?
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
推荐答案
在光标上调用toArray
而不是forEach
:
var a = db.my_collection.find(
{timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20)
.toArray().map(function(o){return o.sid;})
更新
似乎您可以跳过toArray
并直接转到
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;})
这篇关于如何在MongoDB中累积结果(使用forEach?)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文