$documents (aggregation)
On this page
Definition
Syntax
The $documents stage has the following form:
{ $documents: <expression> }
Behavior
$documents accepts any valid expression that resolves to an array of objects. This includes:
-
system variables, such as
$$NOWor$$SEARCH_META -
$letexpressions -
variables in scope from
$lookupexpressions
Expressions that do not resolve to a current document, like $myField or $$ROOT, will result in an error.
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.
[
{ _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
Correlate documents in a collection with other data using $documents to modify $lookup output.
Create the locations collection.
db.locations.insertMany( [ { zip: 94301, name: "Palo Alto" }, { zip: 10019, name: "New York" } ] )
Use $documents as a data source to transform the 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.
[
{
_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
zipfield corresponds to thezip_idfield -
The
asparameter creates a new output field
For details on subqueries using this $lookup syntax, see Correlated Subqueries Using Concise Syntax.