node.js - Nodejs 驱动程序支持哪些聚合游标方法?

标签 node.js mongodb mongoose node-mongodb-native

正如您从 2.6 中了解的那样,Mongodb aggregate() 操作返回一个游标,但是 the behavior is a bit different 与从 find() 返回的普通游标不同。我正在使用 native mongodb nodejs 驱动程序,但找不到有关可用聚合游标方法的适当文档。

例如,不能在聚合游标上运行 count(),但是有两种方法,例如 cursor.objsLeftInBatch()cursor.itcount( ) n mongo 外壳。我在 nodejs native 驱动程序的源代码中找不到它们中的任何一个。 Nodejs 原生驱动或 Mongoose 支持哪些聚合游标方法?

最佳答案

实际上使用游标从聚合返回的是 node transform stream interface与其他一些方便的方法,特别是:

explain: [Function],
get: [Function],
getOne: [Function],
each: [Function],
next: [Function],

您可以通过使用 console.log 简单地转储游标对象来获得。这些应该是不言自明的,get() 方法等同于 .toArray()

因为这是一个标准的流媒体接口(interface),方法和事件处理程序都可以根据这个接口(interface)使用,所以举个例子:

  var MongoClient = require('mongodb').MongoClient;


  MongoClient.connect("mongodb://localhost/test", function(err,db) {

    var items = [];
    var counter = 0;

    var cursor = db.collection('tags').aggregate(
      [
        { "$project": {
          "t1": 1,
          "t2": 1
        }}
      ],
      { "cursor": { "batchSize": 25 } }
    );

    console.log( cursor );

    cursor.on('data', function(data) {
      console.log( this );  // dump the current state info
      items.push( data );
      counter++;
    });

    cursor.on('end', function() {
      console.log( "Iterated " + counter + " times" );
    });

  });

每次游标迭代都会触发“数据”事件,对象上的属性将显示流是完整的还是仍在迭代等等。

关于node.js - Nodejs 驱动程序支持哪些聚合游标方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955533/

相关文章:

arrays - 带有嵌套文档的 $lookup

mongodb - 如何从所有文档中返回数组的嵌套文档

MongoDB - 在另一个字段上使用 $nin

javascript - 使用 Mongoose 在 Handlebars 中渲染额外数据

node.js - express res.download 提供 0 字节文件

javascript - mongoose save 不是使用模式的函数

node.js - 如何将 HTTP REQUEST PUT 与 odata.PUT 结合使用来更新数据库条目?

node.js - 如何刷新 Smartcar 访问 token ?

javascript - 根据货币获取记录

javascript - Mongoose 动态模式字段