Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

$documents (aggregation)

On this page

  • Definition
  • Syntax
  • Behavior
  • Examples
$documents

Changed in version 5.1.

Returns literal documents from input values.

The $documents stage has the following form:

{ $documents: <expression> }

$documents accepts any valid expression that resolves to an array of objects. This includes:

  • system variables, such as $$NOW or $$SEARCH_META

  • $let expressions

  • variables in scope from $lookup expressions

Expressions that do not resolve to a current document, like $myField or $$ROOT, will result in an error.

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 }
]

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 zip field corresponds to the zip_id field

  • The as parameter creates a new output field

For details on subqueries using this $lookup syntax, see Correlated Subqueries Using Concise Syntax.

←  $densify (aggregation)$facet (aggregation) →