Definition
Merges an array of documents into a single document.
Note
Disambiguation
This page describes $mergeObjects when used as an expression, which merges an array of documents.
You can also use $mergeObjects in these other contexts:
$mergeObjects (accumulator), which returns a merged document across a group of input documents.$mergeObjects (window function), which is used in the$setWindowFieldsstage to return a merged document from documents in a window.
Syntax
When used as an expression, $mergeObjects has this syntax:
{ $mergeObjects: <expression> }
The <expression> operand can be either:
A single expression that evaluates to an array of documents to merge. For example,
$blogPostswhere the document fieldblogPostscontains an array of documents.An array of expressions, each of which evaluates to a document. For example,
[ "$doc1", "$doc2", "$doc3" ]where each document field contains a single document.
Behavior
$mergeObjects ignores null input values. If all input values are null, $mergeObjects returns an empty document { }.
$mergeObjects overwrites field values as it merges documents. If multiple input documents contain the same field name, the output contains the value from the last input document that contains the conflicting field.
Example | Results | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| | ||||||||
| | ||||||||
| | ||||||||
| |
Example
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
The following pipeline uses $mergeObjects in $replaceWith to merge each movie's imdb and tomatoes.critic sub-documents into a single ratings document. Both sub-documents contain a rating field, so $mergeObjects overwrites the imdb rating with the tomatoes.critic rating. Unique fields from each sub-document are preserved in the result.
db.movies.aggregate( [ { $match: { genres: "Action", year: 2010, "imdb.rating": { $exists: true }, "tomatoes.critic.rating": { $exists: true } } }, { $sort: { title: 1 } }, { $limit: 5 }, { $replaceWith: { title: "$title", year: "$year", ratings: { $mergeObjects: [ "$imdb", "$tomatoes.critic" ] } } } ] )
In the preceding pipeline:
$matchfilters to Action movies from 2010 with an existingimdb.ratingandtomatoes.critic.rating.$sortsorts documents alphabetically bytitle.$limitrestricts the output to 5 documents to improve readability.$replaceWithuses$mergeObjectsto merge$imdband$tomatoes.criticinto aratingsfield.Because both sub-documents contain a
ratingfield,$mergeObjectsuses the value fromtomatoes.critic(the last argument).The unique fields
votesandidfromimdb, andnumReviewsandmeterfromtomatoes.critic, are all preserved.