$mergeObjects

Combines multiple documents into a single document, merging fields from the input documents with later documents overriding fields from earlier documents.

Syntax

{ $mergeObjects: [<expression1>, <expression2>, ...] }

Parameters

expressionsobjectrequired

Array of expressions that resolve to documents to be merged

Examples

Merge two documents

Combine two document objects into one

Query:

db.products.aggregate([{ $project: { merged: { $mergeObjects: ["$details", "$specifications"] } } }])

Output:

Document with merged field containing combined details and specifications

Merge with literal values

Merge document with literal field values

Query:

db.products.aggregate([{ $project: { result: { $mergeObjects: ["$item", { status: "processed", timestamp: new Date() }] } } }])

Output:

Document with result field containing merged item and literal fields

Conditional merge

Merge documents conditionally based on field existence

Query:

db.products.aggregate([{ $project: { combined: { $mergeObjects: [{ $ifNull: ["$primary", {}] }, { $ifNull: ["$secondary", {}] }] } } }])

Output:

Document with combined field merging primary and secondary objects

Related