On this page本页内容
The $documents
stage has the following form:$documents
阶段具有以下形式:
{ $documents: <expression> }
$documents
accepts any valid expression that resolves to an array of objects. 接受解析为对象数组的任何有效表达式。This includes:这包括:
$$NOW
or $$SEARCH_META
$$NOW
或$$SEARCH_META
$let
$lookup
expressions$lookup
表达式范围内的变量Expressions that do not resolve to a current document, like 不解析为当前文档的表达式,如$myField
or $$ROOT
, will result in an error.$myField
或$$ROOT
,将导致错误。
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 } ]
$documents
with $lookup
$documents
与$lookup
一起使用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' } ] } ]
zip
field corresponds to the zip_id
fieldzip
字段对应于zip_id
字段as
parameter creates a new output fieldas
参数创建一个新的输出字段For details on subqueries using this 有关使用此$lookup
syntax, see Correlated Subqueries Using Concise Syntax.$lookup
语法的子查询的详细信息,请参阅使用简明语法的相关子查询。