如何获得猫鼬聚合函数的结果

时间:2019-01-20 07:03:16

标签: node.js mongodb mongoose

我试图在下面的猫鼬中获得分组依据的结果,这是我的查询

const sumByNetType= await mongoose.connection.db.collection(f)
.aggregate([{$match:{"network_type":n}},{$group: 
{_id:"$network_type",'total': { '$sum': { '$toInt': '$cost' } }}}])

上面的查询给了我聚合构造函数,我想下面给出的是输出

  cursorState:
 { cursorId: null,
 cmd:
  { aggregate: 'dailylogs20190115', pipeline: [Array], cursor: {} },
 documents: [],
 cursorIndex: 0,
 dead: false,
 killed: false,
 init: false,
 notified: false,
 limit: 0,
 skip: 0,
 batchSize: 1000,
 currentLimit: 0,
 transforms: undefined,
 reconnect: true },
 logger: Logger { className: 'Cursor' },
_readableState:
 ReadableState {
 objectMode: true,
 highWaterMark: 16,
 buffer: BufferList { head: null, tail: null, length: 0 },
 length: 0,
 pipes: null,
 pipesCount: 0,
 flowing: null,
 ended: false,
 endEmitted: false,
 reading: false,
 sync: true,
 needReadable: false,
 emittedReadable: false,
 readableListening: false,
 resumeScheduled: false,
 emitClose: true,
 destroyed: false,
 defaultEncoding: 'utf8',
 awaitDrain: 0,
 readingMore: false,
 decoder: null,
 encoding: null },
 readable: true,

我应该怎么做才能得到结果?

1 个答案:

答案 0 :(得分:1)

好吧,所以在研究之后。我看到您到这里的输出是AggregationCursor

我们可以根据需要使用.toArray()轻松地从此处获取文档。 或者,如果有很多文档,您可以使用游标进行迭代。 您可以使用游标做很多事情。签出cursor的文档。

根据您的情况,您只需添加.toArray()即可:

const sumByNetType= await mongoose.connection.db.collection(f)
.aggregate([{$match:{"network_type":n}},{$group: 
{_id:"$network_type",'total': { '$sum': { '$toInt': '$cost' } }}}]).toArray();

如果您要遍历该查询的所有文档, 您可以执行以下操作:

const cursor= await mongoose.connection.db.collection(f)
.aggregate([{$match:{"network_type":n}},{$group: 
{_id:"$network_type",'total': { '$sum': { '$toInt': '$cost' } }}}]);

//this will just iterate over the results
 cursor.each(function(err, docs) {
       console.log(docs)
  // do something using the doc,
        if(docs == null) {
            mongoose.connection.db.close(); //close the connection
      }
  });
相关问题