- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $replaceRoot (aggregation)
$replaceRoot (aggregation)¶
On this page
Definition¶
-
$replaceRoot
¶ New in version 3.4.
Replaces the input document with the specified document. 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).Note
Starting in version 4.2, MongoDB adds a new aggregation pipeline stage
$replaceWith
that is an alias for$replaceRoot
.The
$replaceRoot
stage has the following form:The replacement document can be any valid expression that resolves to a document. The stage errors and fails if
<replacementDocument>
is not a document. For more information on expressions, see Expressions.
Behavior¶
If the <replacementDocument>
is not a document,
$replaceRoot
errors and fails.
If the <replacementDocument>
resolves to a missing document (i.e.
the document does not exist), $replaceRoot
errors and
fails. For example, create a collection with the following
documents:
Then the following $replaceRoot
operation fails because one
of the documents does not have the name
field:
To avoid the error, you can use $mergeObjects
to merge
the name
document into some default document; for example:
Alternatively, you can skip the documents that are missing the name
field by
including a $match
stage to check for existence of the
document field before passing documents to the $replaceRoot
stage:
Or, you can use $ifNull
expression to specify some other
document to be root; for example:
Examples¶
$replaceRoot
with an Embedded Document Field¶
A collection named people
contains the following documents:
The following operation uses the $replaceRoot
stage to
replace each input document with the result of a
$mergeObjects
operation. The $mergeObjects
expression merges the specified default document with the pets
document.
The operation returns the following results:
$replaceRoot
with a Document Nested in an Array¶
A collection named students
contains the following documents:
The following operation promotes the embedded document(s) with the
grade
field greater than or equal to 90
to the top level:
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:
$replaceRoot
with a New Document Created from $$ROOT
and a Default Document¶
Create a collection named contacts
with the following documents:
The following operation uses $replaceRoot
with
$mergeObjects
to output current documents with default
values for missing fields:
The aggregation returns the following documents: