gpt4 book ai didi

mongodb - 迭代具有有限批量大小的 Mongo Cursor

转载 作者:可可西里 更新时间:2023-11-01 10:03:43 26 4
gpt4 key购买 nike

如何遍历以下数据游标?以下代码给出错误“

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

数据变量包含以下内容

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
}

最佳答案

编辑:

来自 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.

您需要发送OP_GET_MORE遍历光标的消息。

改为使用 aggregate() helper .

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

这会返回一个游标。您可以使用 forEach 方法对其进行迭代。

data.forEach(printjson)

关于mongodb - 迭代具有有限批量大小的 Mongo Cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30189894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com