$documents (aggregation)
On this page本页内容
Definition定义
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
阶段
$documents
Stage in a $lookup
StageCorrelate 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' } ]
}
]
Thezip
field corresponds to thezip_id
fieldzip
字段对应于zip_id
字段Theas
parameter creates a new output fieldas
参数创建一个新的输出字段
For details on subqueries using this 有关使用$lookup
syntax, see Correlated Subqueries Using Concise Syntax.$lookup
语法的子查询的详细信息,请参阅使用简明语法的相关子查询。