Docs HomeMongoDB Manual

$documents (aggregation)

Definition定义

$documents

Changed in version 5.1.5.1版更改。

Returns literal documents from input values.从输入值返回文字文档。

Syntax语法

The $documents stage has the following form:$documents阶段具有以下形式:

{ $documents: <expression> }

Behavior行为

$documents accepts any valid expression that resolves to an array of objects. This includes:接受解析为对象数组的任何有效表达式。这包括:

  • system variables, such as $$NOW or $$SEARCH_META系统变量,如$$NOW$$SEARCH_META
  • $let expressions表达式
  • variables in scope from $lookup expressions$lookup表达式作用域中的变量

Expressions that do not resolve to a current document, like $myField or $$ROOT, will result in an error.未解析为当前文档的表达式(如$myField$$ROOT)将导致错误。

Examples实例

Test a Pipeline Stage测试管道阶段

Create testing and debugging data for a pipeline stage without creating test collections.为管道阶段创建测试和调试数据,而不创建测试集合。

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

The aggregation expression does not specify a collection. 聚合表达式未指定集合。It uses the input data in the highlighted $documents stage as input to the $bucketAuto stage.它使用突出显示的$documents阶段中的输入数据作为$bucketAuto阶段的输入。

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

Use a $documents Stage in a $lookup Stage$lookup阶段中使用$documents阶段

Correlate documents in a collection with other data using $documents to modify $lookup output.使用$documents将集合中的文档与其他数据关联,以修改$lookup输出。

Create the locations collection.创建locations集合。

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

Use $documents as a data source to transform the documents.使用$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" }
]
}
]
}
}
]
)

The output correlates the data in the locations collection with the values in the $documents pipeline stage.输出将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' } ]
}
]
  • The zip field corresponds to the zip_id fieldzip字段对应于zip_id字段
  • The as parameter creates a new output fieldas参数创建一个新的输出字段

For details on subqueries using this $lookup syntax, see Correlated Subqueries Using Concise Syntax.有关使用$lookup语法的子查询的详细信息,请参阅使用简明语法的相关子查询