简体   繁体   中英

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'

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 :

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. In 2.6 and later, the aggregate() helper always returns a cursor.

You need to send OP_GET_MORE message to iterate over the cursor.

Instead use the aggregate() helper .

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.

data.forEach(printjson)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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