定義
複数のドキュメントを 1 つのドキュメントに結合します。
$mergeObjects  は、次のステージで使用できます。
構文
$bucket 、 $bucketAuto 、または$groupステージ アキュムレータとして使用する場合、 $mergeObjectsは次の構文をとります。
{ $mergeObjects: <document> } 
($bucket、$bucketAuto、$group ステージに含まれる)他の式でアキュムレータ以外として使用される場合、$mergeObjects は次の構文を持ちます。
{ $mergeObjects: [ <document1>, <document2>, ... ] } 
<document> は、ドキュメントに変換される任意の有効な式にすることができます。
動作
$mergeObjectsはnullオペランドを無視します。 $mergeObjectsへのすべてのオペランドが null に解決されると、 $mergeObjectsは空のドキュメント{ }を返します。
$mergeObjects は、ドキュメントをマージするときにフィールド値を上書きします。マージするドキュメントに同じフィールド名が含まれている場合、結果のドキュメントのフィールドには、そのフィールドに対して最後にマージされたドキュメントの値が含まれます。
| 例 | 結果 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
|  |  | ||||||||
|  |  | ||||||||
|  |  | ||||||||
|  |  | 
例
$mergeObjects
次のドキュメントを使用してコレクション orders を作成します。
db.orders.insertMany( [   { "_id" : 1, "item" : "abc", "price" : 12, "ordered" : 2 },   { "_id" : 2, "item" : "jkl", "price" : 20, "ordered" : 1 } ] ) 
次のドキュメントで別のコレクション items を作成します。
db.items.insertMany( [   { "_id" : 1, "item" : "abc", description: "product 1", "instock" : 120 },   { "_id" : 2, "item" : "def", description: "product 2", "instock" : 80 },   { "_id" : 3, "item" : "jkl", description: "product 3", "instock" : 60 } ] ) 
次の操作では、まず$lookupステージを使用してitemフィールドで 2 つのコレクションを結合し、次に$replaceRootの$mergeObjectsを使用してitemsとordersの結合されたドキュメントをマージします。
db.orders.aggregate( [    {       $lookup: {          from: "items",          localField: "item",    // field in the orders collection          foreignField: "item",  // field in the items collection          as: "fromItems"       }    },    {       $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }    },    { $project: { fromItems: 0 } } ] ) 
この操作により、次のドキュメントが返されます。
{   _id: 1,   item: 'abc',   description: 'product 1',   instock: 120,   price: 12,   ordered: 2 }, {   _id: 2,   item: 'jkl',   description: 'product 3',   instock: 60,   price: 20,   ordered: 1 } 
$mergeObjects アキュムレータとして
次のドキュメントを使用してコレクション sales を作成します。
db.sales.insertMany( [    { _id: 1, year: 2017, item: "A", quantity: { "2017Q1": 500, "2017Q2": 500 } },    { _id: 2, year: 2016, item: "A", quantity: { "2016Q1": 400, "2016Q2": 300, "2016Q3": 0, "2016Q4": 0 } } ,    { _id: 3, year: 2017, item: "B", quantity: { "2017Q1": 300 } },    { _id: 4, year: 2016, item: "B", quantity: { "2016Q3": 100, "2016Q4": 250 } } ] ) 
次の操作では、item フィールドでドキュメントをグループ化する $group ステージで $mergeObjects をアキュムレータとして使用します。
注意
アキュムレータとして使用する場合、 $mergeObjects演算子は単一のオペランドを受け入れます。
db.sales.aggregate( [    { $group: { _id: "$item", mergedSales: { $mergeObjects: "$quantity" } } } ] ) 
この操作により、次のドキュメントが返されます。
{   _id: 'A',   mergedSales: { '2017Q1': 500, '2017Q2': 500, '2016Q1': 400, '2016Q2': 300, '2016Q3': 0, '2016Q4': 0 } }, {   _id: 'B',   mergedSales: { '2017Q1': 300, '2016Q3': 100, '2016Q4': 250 } } 
注意
マージするドキュメントに同じフィールド名が含まれている場合、結果のドキュメントのフィールドには、そのフィールドに対して最後にマージされたドキュメントの値が含まれます。