$documents (聚合)
定义
语法
的$documents
阶段具有以下形式
{ $documents: <expression> }
限制
您只能在数据库级别的聚合管道中使用
$documents
。您必须将
$documents
作为聚合管道的第一个阶段使用。
有关使用示例,请参阅下文。
行为
$documents
接受任何有效的表达式,该表达式解析为对象数组。这包括
无法解析为当前文档的表达式,如 $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 } ]
在 $lookup
阶段中使用 $documents
阶段
使用 $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
语法进行子查询的详细信息,请参阅使用简洁语法的关联子查询。