merge
On this page
The $merge
operator writes the result of an aggregation pipeline to a specified collection.
Syntax
{ $merge: {into: <collection> -or- { db: <db>, coll: <collection> },on: <identifier field>, // Optional,whenMatched: <replace|keepExisting|merge|fail>, // OptionalwhenNotMatched: <insert|discard|fail> // Optional} }
Option |
Type |
Description |
---|---|---|
|
String |
Specifies the collection to write the output to.
or specify a collection in a specified database as:
|
|
String |
Specifies the field that acts as the unique identifier for the document. |
|
String |
Specifies the behavior of the This option can have the following values:
|
|
String |
Specifies the behavior of the This option can have the following three values:
|
Remarks
-
The
$merge
operator does not support thelet
option. -
When the
fail
condition is satisfied, the entire query is aborted.
Example
The following example shows how to use the $merge
operator.
db.getSiblingDB("dbTest").testCol1.insertMany([{ "_id" : 1, Stock_Code: "S01", Area_Code: "A1", Units: 135000, Year: 2018 },{ "_id" : 2, Stock_Code: "S02", Area_Code: "A1", Units: 100000, Year: 2018 },{ "_id" : 3, Stock_Code: "S03", Area_Code: "A1", Units: 125000, Year: 2019 },{ "_id" : 9, Stock_Code: "S04", Area_Code: "A2", Units: 160000, Year: 2019 },{ "_id" : 10, Stock_Code: "S01", Area_Code: "A2", Units: 150000, Year: 2019 }])db.getSiblingDB("dbTest").testCol2.insertMany([{ "_id": 1, Stock_Code: "S03", Area_Code: "A1", Units: 100000, Year: 2017, Comment: "TBA" },{ "_id": 2, Stock_Code: "S04", Area_Code: "A1", Units: 120000, Year: 2017 },{ "_id": 3, Stock_Code: "S01", Area_Code: "A2", Units: 115000, Year: 2017 },{ "_id": 4, Stock_Code: "S03", Area_Code: "A1", Units: 115000, Year: 2018 },{ "_id": 5, Stock_Code: "S04", Area_Code: "A2", Units: 145000, Year: 2018 },])
Now, run the following commands to merge the documents in the testCol1 collection into the testCol2 collection and then list the documents in testCol2:
db.getSiblingDB("dbTest").testCol1.aggregate({ $merge: { into: { db: "dbTest", coll: "testCol2" }, whenMatched: "merge", whenNotMatched: "insert" } })db.testCol2.find()
[
{
_id: 1,
Area_Code: 'A2',
Comment: 'TBA',
Stock_Code: 'S01',
Units: 135000,
Year: 2018
},
{
_id: 2,
Area_Code: 'A1',
Stock_Code: 'S02',
Units: 100000,
Year: 2018
},
{
_id: 3,
Area_Code: 'A1',
Stock_Code: 'S03',
Units: 125000,
Year: 2019
},
{
_id: 4,
Area_Code: 'A1',
Stock_Code: 'S03',
Units: 115000,
Year: 2018
},
{
_id: 5,
Area_Code: 'A2',
Stock_Code: 'S04',
Units: 145000,
Year: 2018
},
{
_id: 9,
Area_Code: 'A2',
Stock_Code: 'S04',
Units: 160000,
Year: 2019
},
{
_id: 10,
Area_Code: 'A2',
Stock_Code: 'S01',
Units: 150000,
Year: 2019
}
]
As specified in the command using the whenMatched: "merge"
and whenNotMatched: "insert"
options, the matching documents are merged and the non matching documents are inserted in the testCol2 collection, respectively.
Last modified: July 28, 2023