On this page本页内容
Note
The following page discusses the 下一页讨论$merge
stage, which outputs the aggregation pipeline results to a collection. $merge
阶段,该阶段将聚合管道结果输出到集合。For a discussion of the 有关将文档合并到单个文档中的$mergeObjects
operator which merges documents into a single document, see $mergeObjects
instead.$mergeObjects
运算符的讨论,请参阅$mergeObjects
。
$merge
¶New in version 4.2.版本4.2中的新功能。
Writes the results of the aggregation pipeline to a specified collection. 将聚合管道的结果写入指定集合。The $merge
operator must be the last stage in the pipeline.$merge
运算符必须是管道中的最后一个阶段。
The $merge
stage:$merge
阶段:
$merge
can output to the same collection that is being aggregated. $merge
可以输出到正在聚合的同一个集合。For a comparison with the 有关与$out
stage which also outputs the aggregation results to a collection, see Comparison with $out.$out
阶段(该阶段也将聚合结果输出到集合)的比较,请参阅与$out
的比较。
On-Demand Materialized Views按需物化视图
$merge
can incorporate the pipeline results into an existing output collection rather than perform a full replacement of the collection. 可以将管道结果合并到现有输出集合中,而不是执行集合的完全替换。This functionality allows users to create on-demand materialized views, where the content of the output collection is incrementally updated when the pipeline is run.此功能允许用户创建按需物化视图,其中输出集合的内容在管道运行时以增量方式更新。
For more information on this use case, see On-Demand Materialized Views as well as the examples on this page.有关此用例的更多信息,请参阅按需物化视图以及本页上的示例。
Materialized views are separate from read-only views. 物化视图与只读视图是分开的。For information on creating read-only views, see read-only views.有关创建只读视图的信息,请参阅只读视图。
$merge
has the following syntax:语法如下所示:
For example:例如:
If using all default options for 如果使用$merge
(including writing to a collection in the same database), you can use the simplified form:$merge
的所有默认选项(包括写入同一数据库中的集合),则可以使用简化形式:
The $merge
takes a document with the following fields:$merge
接受具有以下字段的文档:
into |
Note
| ||||||||||
on |
| ||||||||||
whenMatched |
| ||||||||||
let |
Note
| ||||||||||
whenNotMatched |
|
_id
If the 如果聚合管道结果中的文档中不存在_id
field is not present in a document from the aggregation pipeline results, the $merge
stage generates it automatically._id
字段,则$merge
阶段会自动生成该字段。
For example, in the following aggregation pipeline, 例如,在下面的聚合管道中,$project
excludes the _id
field from the documents passed into $merge
. $project
将_id
字段从传递到$merge
的文档中排除。When 当$merge
writes these documents to the "newCollection"
, $merge
generates a new _id
field and value.$merge
将这些文档写入"newCollection"
时,$merge
会生成一个新的_id
字段和值。
The 如果指定的输出集合不存在,$merge
operation creates a new collection if the specified output collection does not exist.$merge
操作将创建一个新集合。
$merge
writes the first document into the collection and is immediately visible.$merge
将第一个文档写入集合时创建的,并且立即可见。$merge
before the error will not be rolled back.$merge
在错误发生之前完成的任何写入。Note
For a replica set or a standalone, if the output database does not exist, 对于副本集或单机版,如果输出数据库不存在,$merge
also creates the database.$merge
也会创建数据库。
For a sharded cluster, the specified output database must already exist.对于分片群集,指定的输出数据库必须已经存在。
If the output collection does not exist, 如果输出集合不存在,$merge
requires the on identifier to be the _id
field. $merge
要求on标识符为_id
字段。To use a different 若要对不存在的集合使用不同的on
field value for a collection that does not exist, you can create the collection first by creating a unique index on the desired field(s) first. on
字段值,可以先在所需字段上创建唯一索引来创建集合。For example, if the output collection 例如,如果输出集合newDailySales201905
does not exist and you want to specify the salesDate
field as the on identifier:newDailySales201905
不存在,并且希望将salesDate
字段指定为on
标识符:
The $merge
stage can output to a sharded collection. $merge
阶段可以输出到分片集合。When the output collection is sharded, 当输出集合被切分时,$merge
uses the _id
field and all the shard key fields as the default on identifier. $merge
使用_id
字段和所有切分键字段作为默认的on标识符。If you override the default, the on identifier must include all the shard key fields:如果覆盖默认值,on标识符必须包括所有切分键字段:
For example, in a database that has 例如,在启用了分片的数据库中,使用sharding enabled
, use the sh.shardCollection()
method to create a new sharded collection newrestaurants
with the postcode
field as the shard key.sh.shardCollection()
方法创建一个新的分片集合newrestaurants
,并将postcode
字段作为分片键。
The newrestaurants
collection will contain documents with information on new restaurant openings by month (date
field) and postcode (shard key); specifically, the on identifier is ["date", "postcode"]
(the ordering of the fields does not matter). newrestaurants
集合将包含按月份(date
字段)和邮政编码(分片键)列出的新餐厅开业信息的文档;具体来说,on标识符是["date", "postcode"]
(字段的顺序无关紧要)。Because 因为$merge
requires a unique, index with keys that correspond to the on identifier fields, create the unique index (the ordering of the fields do not matter): $merge
需要一个唯一的索引,索引中的键对应于on标识符字段,所以创建唯一索引(字段的顺序无关紧要):[1]
With the sharded collection 创建了分片集合restaurants
and the unique index created, you can use $merge
to output the aggregation results to this collection, matching on [ "date", "postcode" ]
as in the following example:restaurants
和唯一索引后,可以使用$merge
将聚合结果输出到此集合,并在[ "date", "postcode" ]
上进行匹配,如下例所示:
[1] |
|
$merge
) vs Replace Collection ($out
)$merge
)与替换集合($out
)¶如果聚合结果包含一个或多个基于on规范匹配的文档,$merge
can replace an existing document in the output collection if the aggregation results contain a document or documents that match based on the on specification. $merge
可以替换输出集合中的现有文档。As such, 因此,如果聚合结果包括集合中所有现有文档的匹配文档,并且在匹配时指定“替换”,则$merge
can replace all documents in the existing collection if the aggregation results include matching documents for all existing documents in the collection and you specify “replace” for whenMatched.$merge
可以替换现有集合中的所有文档。
However, to replace an existing collection regardless of the aggregation results, use 但是,要替换现有集合而不考虑聚合结果,请使用$out
instead.$out
。
_id
and Shard Key Values_id
和分片键值¶The 如果$merge
errors if the $merge
results in a change to an existing document’s _id
value.$merge
导致现有文档的_id
值发生更改,则$merge
出错。
Tip
To avoid this error, if the on field does not include the 为了避免此错误,如果on字段不包括_id
field, remove the _id
field in the aggregation results to avoid the error, such as with a preceding $unset
stage, etc._id
字段,请删除聚合结果中的_id
字段以避免错误,例如前面的$unset
阶段等。
Additionally, for a sharded collection, 此外,对于分片集合,$merge
also errors if it results in a change to the shard key value of an exising document.$merge
还会在导致现有文档的分片键值发生更改时出错。
Any writes completed by the 在发生错误之前,$merge
before the error will not be rolled back.$merge
完成的任何写入操作都不会回滚。
If the unique index used by 如果$merge
for on field(s) is dropped mid-aggregation, there is no guarantee that the aggregation will be killed. $merge
对on字段使用的唯一索引在聚合过程中被删除,则不能保证聚合将被终止。If the aggregation continues, there is no guarantee that documents do not have duplicate 如果聚合继续进行,则不能保证文档没有重复的on
field values.on
字段值。
If the 如果$merge
attempts to write a document that violates any unique index on the output collection, the operation errors; for example:$merge
试图编写一个文档,该文档违反了输出集合上的任何唯一索引,则操作会出错;例如:
on
字段上的索引。whenMatched
Starting in MongoDB 4.2.2, if all of the following are true for a 从MongoDB 4.2.2开始,如果$merge
stage:$merge
阶段的以下所有条件都成立:
insert
, andinsert
,并且$merge
inserts the document directly into the output collection.$merge
将文档直接插入到输出集合中。
Prior to MongoDB 4.2.2, when these conditions for a 在MongoDB 4.2.2之前,当满足$merge
stage are met, the pipeline specified in the whenMatched field is executed with an empty input document. $merge
阶段的这些条件时,whenMatched字段中指定的管道将使用空输入文档执行。The resulting document from the pipeline is inserted into the output collection.管道生成的文档将插入到输出集合中。
See also参阅
$out
out
的比较¶$merge
and 和$out
Comparison的比较
With the introduction of 随着$merge
, MongoDB provides two stages, $merge
and $out
, for writing the results of the aggregation pipeline to a collection. $merge
的引入,MongoDB提供了两个阶段,$merge
和$out
,用于将聚合管道的结果写入集合。The following summarizes the capabilities of the two stages:以下总结了这两个阶段的功能:
$merge | $out |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Warning
When 当$merge
outputs to the same collection that is being aggregated, documents may get updated multiple times or the operation may result in an infinite loop. $merge
输出到正在聚合的同一个集合时,文档可能会被更新多次,或者该操作可能会导致无限循环。This behavior occurs when the update performed by 当$merge
changes the physical location of documents stored on disk. $merge
执行的更新更改了存储在磁盘上的文档的物理位置时,就会发生这种行为。When the physical location of a document changes, 当文档的物理位置发生变化时,$merge
may view it as an entirely new document, resulting in additional updates. $merge
可能会将其视为一个全新的文档,从而导致额外的更新。For more information on this behavior, see Halloween Problem.有关这种行为的更多信息,请参阅万圣节问题。
Starting in MongoDB 4.4, 从MongoDB 4.4开始,$merge
can output to the same collection that is being aggregated. $merge
可以输出到正在聚合的同一个集合。You can also output to a collection which appears in other stages of the pipeline, such as 您还可以输出到出现在管道的其他阶段的集合,例如$lookup
.$lookup
。
Versions of MongoDB prior to 4.4 did not allow MongoDB 4.4之前的版本不允许$merge
to output to the same collection as the collection being aggregated.$merge
输出到与要聚合的集合相同的集合。
$merge inside a transaction.$merge 。 | |
$merge stage. $merge 阶段。$facet stage), this $merge stage restriction applies to the nested pipelines as well.$facet 阶段),那么$merge 阶段限制也适用于嵌套管道。 | |
$lookup |
$lookup $merge stage.$merge 阶段。 |
$facet |
$facet $merge stage.$merge 阶段。 |
$unionWith |
$unionWith $merge stage.$merge 阶段。 |
"linearizable" |
$merge stage cannot be used in conjunction with read concern "linearizable" . $merge 阶段不能与阅读关注点"linearizable" 一起使用。"linearizable" read concern for db.collection.aggregate() , you cannot include the $merge stage in the pipeline.db.collection.aggregate() 指定“线性化”读取关注点,则不能在管道中包含$merge 阶段。 |
If the output collection does not exist, the 如果输出集合不存在,$merge
creates the collection.$merge
将创建该集合。
For example, a collection named 例如,salaries
in the zoo
database is populated with the employee salary and department history:zoo
数据库中名为salaries
的集合将填充员工薪资和部门历史记录:
You can use the 您可以使用$group
and $merge
stages to initially create a collection named budgets
(in the reporting
database) from the data currently in the salaries
collection:$group
和$merge
阶段从salaries
集合中当前的数据创建一个名为budgets
(在报告数据库中)的集合:
Note
For a replica set or a standalone deployment, if the output database does not exist, 对于副本集或独立部署,如果输出数据库不存在,$merge
also creates the database.$merge
还会创建数据库。
For a sharded cluster deployment, the specified output database must already exist.对于分片群集部署,指定的输出数据库必须已经存在。
$group
stage to group the salaries by the fiscal_year
and dept
.$merge
stage writes the output of the preceding $group
stage to the budgets
collection in the reporting
database.To view the documents in the new 要查看新budgets
collection:budgets
集合中的文档,请执行以下操作:
The budgets
collection contains the following documents:budgets
集合包含以下文档:
See also参阅
The following example refers to the collections from the previous example.以下示例引用上一示例中的集合。
The example 示例salaries
collection contains the employee salary and department history:salaries
集合包含员工薪资和部门历史记录:
The example 示例budgets
collection contains the cumulative yearly budgets:budgets
集合包含累积年度预算:
During the current fiscal year (在当前财政年度(本例中为2019
in this example), new employees are added to the salaries
collection and new head counts are pre-allocated for the next year:2019
年),新员工将被添加到salaries
集合中,新员工将被预先分配到下一年:
To update the 要更新budgets
collection to reflect the new salary information, the following aggregation pipeline uses:budgets
集合以反映新的薪资信息,使用以下聚合管道:
$match
fiscal_year
greater than or equal to 2019
.fiscal_year
(财政年度)大于或等于2019
年的所有文件。$group
fiscal_year
and dept
.fiscal_year
(财政年度)和dept
(部门)对工资进行分组。$merge
budgets
collection, replacing documents with the same _id
value (in this example, a document with the fiscal year and dept). budgets
集合,请使用相同的_id
值替换文档(在本例中,是一个带有会计年度和部门的文档)。$merge
inserts the new documents.$merge
将插入新文档。After the aggregation is run, view the documents in the 运行聚合后,查看budgets
collection:budgets
集合中的文档:
The budgets
collection incorporates the new salary data for fiscal year 2019 and adds new documents for fiscal year 2020:budgets
集合包含2019财年的新工资数据,并添加2020财年的新文件:
See also参阅
To ensure that the 要确保$merge
does not overwrite existing data in the collection, set whenMatched to keepExisting or fail.$merge
不会覆盖集合中的现有数据,请将whenMatched设置为keepExisting或fail。
The example salaries
collection in the zoo
database contains the employee salary and department history:zoo
数据库中的示例salaries
集合包含员工薪资和部门历史记录:
A collection orgArchive
in the reporting
database contains historical departmental organization records for the past fiscal years. reporting
数据库中的集合orgArchive
包含过去会计年度的部门组织历史记录。Archived records should not be modified.存档记录不应被修改。
The orgArchive
collection has a unique compound index on the fiscal_year
and dept
fields; i.e. there should be at most one record for the same fiscal year and department combination:orgArchive
集合在fiscal_year
字段和dept
字段上有一个唯一的复合索引;亦即,同一财年和部门组合最多应有一项记录:
At the end of current fiscal year (在本财年末(本例中为2019
in this example), the salaries
collection contain the following documents:2019
年),salaries
集合包含以下文件:
To update the 要更新orgArchive
collection to include the fiscal year 2019
that has just ended, the following aggregation pipeline uses:orgArchive
集合以包括刚刚结束的2019
财年,以下聚合管道使用:
$match
fiscal_year
equal to 2019
.fiscal_year
等于2019
年的所有文件。$group
fiscal_year
and dept
.fiscal_year
和dept
对员工进行分组。$project
_id
field and add separate dept
and fiscal_year
field. _id
字段,并添加单独的dept
和fiscal_year
字段。$merge
, $merge
automatically generates a new _id
field for the documents.$merge
时,$merge
会自动为文档生成一个新的_id
字段。$merge
orgArchive
.orgArchive
。
The $merge
stage matches documents on the dept
and fiscal_year
fields and fails
when matched. $merge
阶段匹配dept
和fiscal_year
字段中的文档,匹配时失败。That is, if a document already exists for the same department and fiscal year, the 也就是说,如果同一部门和财政年度的文档已经存在,$merge
errors.$merge
出错。
After the operation, the 操作完成后,orgArchive
collection contains the following documents:orgArchive
集合包含以下文档:
If the 如果orgArchive
collection already contained a document for 2019 for department "A"
and/or "B"
, the aggregation fails because of the duplicate key error. orgArchive
集合中已包含部门"A"
和/或"B"
2019年的文档,则由于重复密钥错误,聚合失败。However, any document inserted before the error will not be rolled back.但是,在错误发生之前插入的任何文档都不会回滚。
If you specify keepExisting for the matching document, the aggregation does not affect the matching document and does not error with duplicate key error. 如果为匹配文档指定keepExisting,则聚合不会影响匹配文档,也不会出现重复密钥错误。Similarly, if you specify replace, the operation would not fail; however, the operation would replace the existing document.同样,如果指定replace,操作也不会失败;然而,该行动将取代现有文件。
By default, if a document in the aggregation results matches a document in the collection, the 默认情况下,如果聚合结果中的文档与集合中的文档匹配,则$merge
stage merges the documents.$merge
阶段会合并这些文档。
An example collection 示例集合purchaseorders
is populated with the purchase order information by quarter and regions:purchaseorders
按季度和地区填充采购订单信息:
Another example collection 另一个示例集合reportedsales
is populated with the reported sales information by quarter and regions:reportedsales
按季度和地区填充报告的销售信息:
Assume that, for reporting purposes, you want to view the data by quarter in the following format:假设出于报告目的,您希望按季度以以下格式查看数据:
You can use the 您可以使用$merge
to merge in results from the purchaseorders
collection and the reportedsales
collection to create a new collection quarterlyreport
.$merge
合并来自purchaseorders
集合和reportedsales
集合的结果,以创建新的集合 quarterlyreport
。
To create the 要创建quarterlyreport
collection, you can use the following pipeline:quarterlyreport
集合,可以使用以下管道:
The $group
stage groups by the quarter and uses $sum
to add the qty
fields into a new purchased
field. $group
阶段按季度分组,并使用$sum
将qty
字段添加到新purchased
字段中。For example:例如:
merge
stage writes the documents to the quarterlyreport
collection in the same database. merge
阶段将文档写入同一数据库中的quarterlyreport
集合。_id
field, the stage merges the matching documents. _id
字段匹配的现有文档,则阶段会合并匹配的文档。To view the documents in the collection, run the following operation:要查看集合中的文档,请运行以下操作:
The collection contains the following documents:该集合包含以下文档:
Similarly, run the following aggregation pipeline against the 类似地,对reportedsales
collection to merge the sales results into the quarterlyreport
collection.reportedsales
集合运行以下聚合管道,以将销售结果合并到quarterlyreport
集合中。
The $group
stage groups by the quarter and uses $sum
to add the qty
fields into a new sales
field. $group
阶段按季度分组,并使用$sum
将qty
字段添加到新sales
字段中。For example:例如:
merge
stage writes the documents to the quarterlyreport
collection in the same database. merge
阶段将文档写入同一数据库中的quarterlyreport
集合。_id
field (the quarter), the stage merges the matching documents. _id
字段(季度)匹配的现有文档,则阶段会合并匹配的文档。To view the documents in the 要在合并数据后查看quarterlyreport
collection after the data has been merged, run the following operation:quarterlyreport
集合中的文档,请运行以下操作:
The collection contains the following documents:该集合包含以下文档:
The 当文档匹配时,$merge
can use a custom update pipeline when documents match. $merge
可以使用自定义更新管道。The whenMatched pipeline can have the following stages:whenMatched
管道可分为以下几个阶段:
$addFields
$set
$project
$unset
$replaceRoot
$replaceWith
An example collection 示例集合votes
is populated with the daily vote tally. votes
使用每日投票计数填充。Create the collection with the following documents:使用以下文档创建集合:
Another example collection 另一个示例集合monthlytotals
has the up-to-date monthly vote totals. monthlytotals
有最新的每月投票总数。Create the collection with the following document:使用以下文档创建集合:
At the end of each day, that day’s votes is inserted into the 每天结束时,当天的投票将被插入votes
collection:votes
集合:
You can use 您可以将$merge
with an custom pipeline to update the existing document in the collection monthlytotals
:$merge
与自定义管道一起使用,以更新集合monthlytotals
中的现有文档:
The $match
stage finds the specific day’s votes. $match
阶段查找特定日期的投票。For example:例如:
The $project
stage sets the _id
field to a year-month string. $project
阶段将_id
字段设置为年-月字符串。For example:例如:
The merge
stage writes the documents to the monthlytotals
collection in the same database. merge
阶段将文档写入同一数据库中的monthlytotals
集合。If the stage finds an existing document in the collection that matches on the 如果stage在集合中找到与_id
field, the stage uses a pipeline to add the thumbsup
votes and the thumbsdown
votes._id
字段匹配的现有文档,则阶段将使用管道添加thumbsup
投票和thumbsdown
投票。
thumbsup
field and the thumbsdown
field in the results document, the pipeline uses the $$new
variable; i.e. $$new.thumbsup
and $new.thumbsdown
.thumbsup
字段和thumbsdown
字段,管道使用$$new
变量;比如$$new.thumbsup
和$new.thumbsdown
。thumbsup
field and the thumbsdown
field in the existing document in the collection; i.e. $thumbsup
and $thumbsdown
.thumbsup
字段和thumbsdown
字段;比如$thumbsup
和$thumbsdown
。The resulting document replaces the existing document.生成的文档将替换现有文档。
To view documents in the 要在合并操作后查看monthlytotals
collection after the merge operation, run the following operation:monthlytotals
集合中的文档,请运行以下操作:
The collection contains the following document:该集合包含以下文档: