对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$documents(聚合阶段)

$documents

6.0版本新增。

根据输入值返回字面文档。

$documents 阶段具有以下形式:

{ $documents: <expression> }
  • 您只能在数据库级聚合管道中使用$documents 。

  • 您必须使用$documents作为聚合管道的第一阶段。

请参阅下面的使用示例。

$documents 接受解析为对象数组的任何有效表达式。这包括:

  • 系统变量,如$$NOW或 $$SEARCH_META

  • $let 表达式

  • $lookup 表达式范围内的变量

无法解析为当前文档的表达式(如 $myField 或 $$ROOT)会导致错误。

为管道阶段创建测试和调试数据,而无需创建测试集合。

db.aggregate( [ { $documents: [ { x: 10 }, { x: 2 }, { x: 5 } ] }, { $bucketAuto: { groupBy: "$x", buckets: 4 } } ])

聚合表达式未指定集合。它使用突出显示的 $documents 阶段中的输入数据作为 $bucketAuto 阶段的输入。

[ { _id: { min: 2, max: 5 }, count: 1 }, { _id: { min: 5, max: 10 }, count: 1 }, { _id: { min: 10, max: 10 }, count: 1 }]

使用 $documents 将集合中的文档与其他数据关联,从而修改 $lookup 输出。

创建 locations 集合。

db.locations.insertMany( [ { zip: 94301, name: "Palo Alto" }, { zip: 10019, name: "New York" } ] )

将 $documents 作为数据源对文档进行转化。

db.locations.aggregate( [ { $match: {} }, { $lookup: { localField: "zip", foreignField: "zip_id", as: "city_state", pipeline: [ { $documents: [ { zip_id: 94301, name: "Palo Alto, CA" }, { zip_id: 10019, name: "New York, NY" } ] } ] } } ] )

输出内容会将 locations 集合中的数据与 $documents 管道阶段中的值进行关联。

[ { _id: ObjectId("618949d60f7bfd5f5689490d"), zip: 94301, name: 'Palo Alto', city_state: [ { zip_id: 94301, name: 'Palo Alto, CA' } ] }, { _id: ObjectId("618949d60f7bfd5f5689490e"), zip: 10019, name: 'New York', city_state: [ { zip_id: 10019, name: 'New York, NY' } ] }]
  • zip 字段与 zip_id 字段对应

  • as 参数会创建一个新的输出字段

有关使用 $lookup 语法的子查询的详细信息,请参阅使用简洁事务语法的关联子查询。