$replaceRoot (aggregation)
On this page
Definition
-
$replaceRoot
-
New in version 3.4.
Promotes a specified document to the top level and replaces all other fields. The operation replaces all existing fields in the input document, including the
_id
field. You can promote an existing embedded document to the top level, or create a new document for promotion (see example).The
$replaceRoot
stage has the following form:The replacement document can be any valid expression that resolves to a document.
For more information on expressions, see Expressions.
Behavior
$replaceRoot
operations fail with an error if <replacementDocument>
is not a document.
If the replacement document refers to a field in the input document that does not exist, the operation fails with an error. To ensure that the replacement document exists, use a $match
stage first to check for existence before passing documents to the $replaceRoot
stage (see example).
Examples
$replaceRoot
with an embedded document
A collection named produce
contains the following documents:
The following operation uses the $replaceRoot
stage to promote the in_stock
document to the top level, discarding the current top level fields.
The operation returns the following documents:
$replaceRoot
with a $match
stage
A collection named people
contains the following documents:
In order to run an aggregation operation with a $replaceRoot
stage to promote the pets
field to the top level, you need to also include a $match
stage to filter out any documents which do not contain a pets
field.
The operation returns the following results:
$replaceRoot
with a newly created document
You can also create new documents as part of the $replaceRoot
stage and use them to replace all the other fields.
A collection named contacts
contains the following documents:
The following operation creates a new document out of the first_name
and last_name
fields.
The operation returns the following results: