Javascript MongoDB - 不明白如何使用游标循环遍历集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10904436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:30:31  来源:igfitidea点击:

MongoDB - dont understand how to loop through collections with a cursor

javascriptmongodbmongoid

提问by Genadinik

advertisers = db.dbname.find( 'my query which returns things correctly' );

I realize now that it returns a cursor to the list of collections.

我现在意识到它返回一个指向集合列表的游标。

But I am not sure how to loop through them and get each collection.

但我不确定如何遍历它们并获取每个集合。

I want to try something like this:

我想尝试这样的事情:

advertisers.each(function(err, advertiser) {
    console.log(advertiser);
});

But that does not work. But I didn't see from searching online how to make it actually work with simple JavaScript.

但这不起作用。但是我没有从网上搜索中看到如何使它与简单的 JavaScript 一起工作。

Then I have this code:

然后我有这个代码:

var item;

if ( advertisers != null )
{
   while(advertisers.hasNext()) 
   { 
      item = advertisers.next();
   }
}

and it gives this error: SyntaxError: syntax error (shell):1

它给出了这个错误: SyntaxError: syntax error (shell):1

Help much appreciated!

非常感谢帮助!

Thanks!

谢谢!

回答by Justin Thomas

The quick and dirty way is:

快速而肮脏的方法是:

var item;
var items = db.test.find();
while(items.hasNext()) {
   item = items.next();
   /* Do something with item */
}

There is also the more functional:

还有更实用的:

items.forEach(function(item) {
   /* do something */
});

回答by Neno

One more way to loop through collections is using toArray cursor's method:

循环遍历集合的另一种方法是使用 toArray 游标的方法:

var results = db.getCollection('posts').find({}).toArray();

for(var i = 0; i <= results.length -1; i++)
{
    print("Author is:" + results[i].Author);
}

回答by LuisCarlos Rodriguez

Since you are not showing the stack then I assume your problem is the parameter you are passing to the find function, this parameter has to be a JavaScript object, therefore:

由于您没有显示堆栈,因此我认为您的问题是您传递给 find 函数的参数,该参数必须是一个 JavaScript 对象,因此:

var query = {
    key: 'my query which returns things correctly'
}

advertisers = db.dbname.find(query);
advertisers.each (function(err, doc){

    //.... error code not included.....
    console.log(doc);
});