Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$documents(聚合)

在此页面上

  • 定义
  • 语法
  • 行为
  • 举例
$documents

版本5中的新增功能。 1 :(也可在5 . 0 . 3中使用

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

$documents阶段具有以下形式:

{ $documents: <expression> }

$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 语法进行子查询的详细信息,请参阅使用简明语法的相关子查询。

← $densify(聚合)