- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $mergeObjects (aggregation)
$mergeObjects (aggregation)¶
On this page
Definition¶
-
$mergeObjects
¶ New in version 3.6.
Combines multiple documents into a single document.
When used as a
$group
stage accumulator,$mergeObjects
has the following form:When used in other expressions, including in the
$group
stage but not as an accumulator:
The
<document>
can be any valid expression that resolves to a document.
Behavior¶
mergeObjects
ignoresnull
operands. If all the operands tomergeObjects
resolves to null,mergeObjects
returns an empty document{ }
.mergeObjects
overwrites the field values as it merges the documents. If documents to merge include the same field name, the field, in the resulting document, has the value from the last document merged for the field.
Example | Results |
---|---|
Examples¶
$mergeObjects
¶
Create a collection orders
with the following documents:
Create another collection items
with the following documents:
The following operation first uses the $lookup
stage to
join the two collections by the item
fields and then uses
$mergeObjects
in the $replaceRoot
to merge
the joined documents from items
and orders
:
The operation returns the following documents:
$mergeObjects
as an Accumulator¶
Create a collection sales
with the following documents:
The following operation uses $mergeObjects
as a
accumulator in a $group
stage that groups documents by the
item
field:
Note
When used as an accumulator, $mergeObjects
operator
accepts a single operand.
The operation returns the following documents:
Note
If the documents to merge include the same field name, the field in the resulting document has the value from the last document merged for the field.