【问题标题】:How to set 'cursor' option in Aggregate MongoDB如何在 Aggregate MongoDB 中设置“光标”选项
【发布时间】:2018-08-16 19:10:11
【问题描述】:

我的 API 服务器上有一个聚合命令。在我将 MongoDB 更新到 3.6.3 之前,它运行良好。现在我收到这种错误:“需要'cursor'选项,除了带有解释参数的聚合”。 这是我的例子:

ArchiveReq.aggregate({
                $project: {
                    projectId: 1,                       
                    projectName: 1,
                    shortDescription: 1,
                    numOfStudents: 1,
                    creationDate: 1,
                    matches: {$ne: ['$creationDate', '$updateDate']}
                }
            },
            function (err, Requests) {              
                if (err)
                    return res.send(err)

                res.json(Requests);
            }
        ); 

【问题讨论】:

    标签: angularjs node.js mongodb mongoose aggregate


    【解决方案1】:
    ArchiveReq.aggregate([
                        $project: {
                        projectId: 1,                       
                        projectName: 1,
                        shortDescription: 1,
                        numOfStudents: 1,
                        creationDate: 1,
                        matches: {$ne: ['$creationDate', '$updateDate']}
                        }
                         ],
                         {
                           cursor: { batchSize: 0 }
                         }
                       ).exec(function(error, cursor) {
    
                       // use cursor 
    
                       });
    

    在 3.4 版中更改:MongoDB 3.6 删除了不带游标选项的聚合命令的使用,除非该命令包含说明选项。除非包含说明选项,否则必须指定游标选项。示例:

    要使用默认批量大小指示游标,请指定游标:{}。

    要使用非默认批量大小指示游标,请使用 cursor: { batchSize: }。

    以下示例对文章集合执行聚合操作,以计算出现在集合中的 tags 数组中每个不同元素的计数。有关更多详细信息,请参阅https://docs.mongodb.com/manual/reference/command/aggregate/

    db.runCommand( {
       aggregate: "articles",
       pipeline: [
          { $project: { tags: 1 } },
          { $unwind: "$tags" },
          { $group: { _id: "$tags", count: { $sum : 1 } } }
       ],
       cursor: { }
    } )
    

    【讨论】:

    • 如何在我的示例中实现它?
    • 尝试使用 MyModel.aggregate([]).cursor({ batchSize: 2500, async: true }).exec(function(error, cursor) { // 使用光标 });
    • 我在游标中找不到关于我的收藏的任何信息,如何将其返回给客户?
    【解决方案2】:

    如果你想在 mongo 3.6 中使用聚合函数

    你可以试试这个

    let resArchiveReq= await ArchiveReq.aggregate([
                    { ... }
                ]).cursor({}).exec().toArray()
    
            return res.json({ result: resArchiveReq })
    

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 2023-02-13
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2021-11-19
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多