简体   繁体   English

在批处理大小有限的Mongo游标上迭代

[英]iterating over a Mongo Cursor with finite batch size

How can I iterate over the following data cursor? 如何遍历以下数据游标? Following code gives error " 以下代码给出错误“

TypeError: Object [object Object] has no method 'forEach' TypeError:对象[object Object]没有方法'forEach'

var data = db.profiles.runCommand("aggregate", {
    pipeline: [
        {$limit: 100000},
        {$unwind: "$Items"},
        {   $group: {
                _id: "$Items", count: {$sum: 1}
            },
        },
    ],
    allowDiskUse: true,
    cursor: { batchSize: 100 }
});

data.forEach(printjson) // gives error

data variable contains the following content 数据变量包含以下内容

MongoDB shell version: 2.6.5
connecting to: myCollection

    {
        "cursor" : {
            "id" : NumberLong("61248019114"),
            "ns" : "myCollection.profiles",
            "firstBatch" : [
                {
                    "_id" : "alex",
                    "count" : 1
                },
                {
                    "_id" : "james",
                    "count" : 1
                } .......
            },
        "ok" : 1
    }

EDIT : 编辑:

From MongoDB RunCommand Docs : 从MongoDB RunCommand Docs中

Using the aggregate command to return a cursor is a low-level operation, intended for authors of drivers. 使用聚合命令返回游标是一种低级操作,旨在供驱动程序的作者使用。 Most users should use the db.collection.aggregate() helper provided in the mongo shell or in their driver. 大多数用户应使用mongo shell或驱动程序中提供的db.collection.aggregate()帮助程序。 In 2.6 and later, the aggregate() helper always returns a cursor. 在2.6及更高版本中,aggregate()帮助器始终返回游标。

You need to send OP_GET_MORE message to iterate over the cursor. 您需要发送OP_GET_MORE消息以遍历游标。

Instead use the aggregate() helper . 而是使用aggregate()助手

var data= db.profiles.aggregate([
    {$limit: 100000},
        {$unwind: "$Items"},
        {   $group: {
                _id: "$Items", count: {$sum: 1}
            },
        },
    ],
    {
        allowDiskUse: true,
        cursor: { batchSize: 100}
    }
)

This returns you a cursor. 这将返回一个游标。 You can use forEach method for iterating it. 您可以使用forEach方法进行迭代。

data.forEach(printjson)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM