简体   繁体   English

与Node.js一起使用时,MongoDB游标如何工作?

[英]How do MongoDB cursors work when used with Node.js?

I am using Node.js with the npm package mongodb . 我正在将Node.js与npm软件包mongodb When I use findOne(...) , I get a result which is directly the item I searched for. 当我使用findOne(...) ,得到的结果直接就是我搜索的项目。 When I use find(...) instead, I don't get an array of elements, I get a cursor which looks very weird if you console.log it. 当我改用find(...) ,没有得到一个元素数组,但得到一个游标,如果您console.log它,它看起来很奇怪。

My question is why does it return a cursor instead of the array of elements and is the cursor.forEach(...) call then asynchronous or how can the client get data out of the cursor? 我的问题是为什么它返回一个游标而不是元素数组,并且cursor.forEach(...)调用然后是异步的,或者客户端如何从游标中获取数据?

It returns a cursor instead of an array to provide flexibility to the client to access the results in whatever way is optimal for its needs. 它返回游标而不是数组,以向客户端提供灵活性,使其以最适合其需求的方式访问结果。

To get an array of all results, you can call the async toArray method on the cursor: 要获取所有结果的数组,可以在游标上调用async toArray方法:

collection.find({...}).toArray((err, docs) => {...});

Same thing for aggregate : 对于aggregate同样的事情:

collection.aggregate([{$match: {...}}]).toArray((err, docs) => {...});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM