Aggregation issue with Mongo 3.6

删除回忆录丶 提交于 2019-12-02 00:11:55

In mongo 3.6 there has been changes while using aggregate you have to use cursor, unless you include the explain option, you must specify the cursor option. I faced same error as you were facing. Now you have to do it like

this.aggregate( [
        { $unwind : "$tags" },
        {$group: {_id: '$tags', count: { $sum: 1} }},
        {$sort: { count: 1 }}
            ] ).cursor({}).exec();

Now you can use cursor method cursor.toArray() to return an array that contains all the documents from a cursor. Cursors returned from aggregation only supports cursor methods that operate on evaluated cursors like cursor.toArray(), to know about more cursor methods you can click here and get further.

In Node.js, after upgrade MongoDB from 3.4 to 3.6, there are 2 things that need to check:

  1. Add cursor: {} option in the aggregate statement. In previous MongoDB version, this is optional (Of course, you can define batchSize in cursor object if you want). For example:

    db.collection(collectionName).aggregate(pipelineArray, {
      cursor: {}
    }, function(error, result) {
      ...
    });
    
  2. If the above code hang and the callback is not invoked, please check the mongodb driver version. I get this "not responding" problem in mongodb module v2.2.16. After upgrade mongodb to v2.2.35, it's fixed.

For those with issues trying to figure out a complete example on 3.6, this worked for me :

   db.collection(collectionName).aggregate([
        {
            $lookup: lookUpOption
        },
        {
            $match: matchOption
        }
    ],{cursor: {}},null).toArray(function(err, docs) {
        console.log("returned data is : ", docs);
        db.close();
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!