【问题标题】:How to get the result of mongoose aggregate function如何得到猫鼬聚合函数的结果
【发布时间】:2019-01-20 07:03:16
【问题描述】:

我正在尝试在下面给出的 mongoose 中获取 group by 的结果是我的查询

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,

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

【问题讨论】:

  • 嘿,您是否尝试过定义模型或模式并在其中使用聚合?无需在顶层直接聚合
  • @saikatchakrabortty 先生的问题是我有许多预先存在的集合,例如daily0、daily1、daily2、.....dailyn,所以我基本上很困惑,我应该为每个预先存在的集合制作模型或模式
  • 嘿,已经添加了答案,如果有效,别忘了点赞;)

标签: node.js mongodb mongoose


【解决方案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
      }
  });

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 2015-08-04
    • 2018-08-23
    • 2021-12-07
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2018-07-30
    • 2017-01-23
    相关资源
    最近更新 更多