“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

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

后退

$densify(聚合)

来年

$facet(聚合)