MongoDB批量聚合查询结果?

问题描述 投票:0回答:1

假设我有一个带有模式的收藏帖子

{
 _id,
 userId,
 name,
 createdAt,
 location,
 teamId
}

我想按 userId 对数据进行分组

{
        $match: {
          teamId: new ObjectId(teamId),
          createdAt: { $gte: startTime, $lte: endTime },
        },
      },
      {
        $group: {
          _id: "$userId",
          posts: { $push: "$$ROOT" },
        },
      },

现在我想要 100 个批次的数据,我将循环第一个批次并执行一些操作,然后我必须循环下一个批次,依此类推。我怎样才能用nodejs的mongoDb包来做这件事?

mongodb mongodb-query
1个回答
0
投票

您已经收到 1,000 个批次的文档:https://github.com/mongodb/node-mongodb-native/blob/bb5fa43ce58f11d4961f1feaa0d6e58ef6bd8378/src/cursor/abstract_cursor.ts#L740

您可以在查询时在游标选项中更改此数字https://www.mongodb.com/docs/manual/reference/command/aggregate/#aggregate-data-specifying-batch-size

但坦白说,这是相当低的水平。通常不需要触摸它。驱动程序负责幕后的后勤工作,以便您可以使用简单的顶级 API https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/read-operations/cursor/#异步迭代,只需迭代游标一次获取一个文档:

for await (const doc of cursor) {
    console.log(doc); // or whatever actions you wanted to do with the document
}

它实际上循环第一批,当它结束时,它会发出

getMore
请求检索下一批:https://github.com/mongodb/node-mongodb-native/blob/bb5fa43ce58f11d4961f1feaa0d6e58ef6bd8378/src/cursor/abstract_cursor .ts#L743 并将下一个文档返回给迭代器。

© www.soinside.com 2019 - 2024. All rights reserved.