Docs HomeMongoDB Manual

$unionWith (aggregation)

Definition定义

$unionWith

New in version 4.4. 4.4版新增。

Performs a union of two collections. 执行两个集合的并集。$unionWith combines pipeline results from two collections into a single result set. $unionWith将来自两个集合的管道结果组合为一个结果集。The stage outputs the combined result set (including duplicates) to the next stage.该阶段将组合的结果集(包括重复项)输出到下一阶段。

The order in which the combined result set documents are output is unspecified.未指定组合结果集文档的输出顺序。

Syntax语法

The $unionWith stage has the following syntax:$unionWith阶段具有以下语法:

{ $unionWith: { coll: "<collection>", pipeline: [ <stage1>, ... ] } }

To include all documents from the specified collection without any processing, you can use the simplified form:要包含指定集合中的所有文档而不进行任何处理,可以使用简化的表单:

{ $unionWith: "<collection>" }  // Include all documents from the specified collection

The $unionWith stage takes a document with the following fields:$unionWith阶段接受一个包含以下字段的文档:

Field字段Description描述
collThe collection or view whose pipeline results you wish to include in the result set. 要将其管道结果包含在结果集中的集合或视图。
pipelineOptional.可选的。An aggregation pipeline to apply to the specified coll.要应用于指定coll的聚合管道。
[ <stage1>, <stage2>, ...]
The pipeline cannot include the $out and $merge stages. 管道不能包括$out$merge阶段。Starting in v6.0, the pipeline can contain the Atlas Search $search stage as the first stage inside the pipeline. 从v6.0开始,pipeline可以包含Atlas Search$Search阶段作为管道内的第一个阶段。To learn more, see Atlas Search Support.要了解更多信息,请参阅Atlas Search Support

The $unionWith operation would correspond to the following SQL statement:$unionWith操作将对应于以下SQL语句:

SELECT *
FROM Collection1
WHERE ...
UNION ALL
SELECT *
FROM Collection2
WHERE ...

Considerations注意事项

Duplicate Results重复的结果

The combined results from the previous stage and the $unionWith stage can include duplicates.上一阶段和$unionWith阶段的组合结果可能包括重复项。

For example, create a suppliers collection and a warehouses collection:例如,创建suppliers集合和warehouses集合:

db.suppliers.insertMany([
{ _id: 1, supplier: "Aardvark and Sons", state: "Texas" },
{ _id: 2, supplier: "Bears Run Amok.", state: "Colorado"},
{ _id: 3, supplier: "Squid Mark Inc. ", state: "Rhode Island" },
])
db.warehouses.insertMany([
{ _id: 1, warehouse: "A", region: "West", state: "California" },
{ _id: 2, warehouse: "B", region: "Central", state: "Colorado"},
{ _id: 3, warehouse: "C", region: "East", state: "Florida" },
])

The following aggregation combines the state field projection results from the suppliers and warehouse collections.以下聚合组合了来自supplierswarehouse集合的state字段投影结果。

db.suppliers.aggregate([
{ $project: { state: 1, _id: 0 } },
{ $unionWith: { coll: "warehouses", pipeline: [ { $project: { state: 1, _id: 0 } } ]} }
])

The result set contains duplicates:结果集包含重复项:

{ "state" : "Texas" }
{ "state" : "Colorado" }
{ "state" : "Rhode Island" }
{ "state" : "California" }
{ "state" : "Colorado" }
{ "state" : "Florida" }

To remove the duplicates, you can include a $group stage to group by the state field:要删除重复项,可以包含$group阶段以按state字段分组:

db.suppliers.aggregate([
{ $project: { state: 1, _id: 0 } },
{ $unionWith: { coll: "warehouses", pipeline: [ { $project: { state: 1, _id: 0 } } ]} },
{ $group: { _id: "$state" } }
])

The result set no longer contains duplicates:结果集不再包含重复项:

 { "_id" : "California" }
{ "_id" : "Texas" }
{ "_id" : "Florida" }
{ "_id" : "Colorado" }
{ "_id" : "Rhode Island" }

$unionWith a Sharded Collection分片集合

If the $unionWith stage is part of the $lookup pipeline, the $unionWith coll cannot be sharded. 如果$unionWith阶段是$lookup pipeline的一部分,则不能对$unionWith coll进行分片。For example, in the following aggregation operation, the inventory_q1 collection cannot be sharded:例如,在以下聚合操作中,inventory_q1集合无法进行分片:

db.suppliers.aggregate([
{
$lookup: {
from: "warehouses",
let: { order_item: "$item", order_qty: "$ordered" },
pipeline: [
...
{ $unionWith: { coll: "inventory_q1", pipeline: [ ... ] } },
...
],
as: "stockdata"
}
}
])

Collation排序规则

If the db.collection.aggregate() includes a collation, that collation is used for the operation, ignoring any other collations.如果db.collection.aggregate()包含collation,则该排序规则将用于操作,而忽略任何其他排序规则。

If the db.collection.aggregate() does not include a collation, the db.collection.aggregate() method uses the collation for the top-level collection/view on which the db.collection.aggregate() is run:如果db.collection.aggregate()不包括collation,则db.collection.aggregate()方法将使用运行db.collection.aggregate()的顶级集合/视图的排序规则:

  • If the $unionWith coll is a collection, its collation is ignored.如果$unionWith coll是一个集合,则会忽略其排序规则。
  • If the $unionWith coll is a view, then its collation must match that of the top-level collection/view. Otherwise, the operation errors.如果$unionWith coll是一个视图,则其排序规则必须与顶级集合/视图的排序规则匹配。否则,操作将出错。

Atlas Search SupportAtlas搜索支持

Starting in MongoDB 6.0, you can specify the Atlas Search $search or $searchMeta stage in the $unionWith pipeline to search collections on the Atlas cluster. 从MongoDB 6.0开始,您可以在$unionWith管道中指定Atlas Search $search$searchMeta阶段来搜索Atlas集群上的集合。The $search or the $searchMeta stage must be the first stage inside the $unionWith pipeline.$search$searchMeta阶段必须是$unionWith管道内的第一个阶段。

[{
"$unionWith": {
"coll": <collection-name>,
"pipeline": [{
"$search": {
"<operator>": {
<operator-specification>
}
},

...
}]
}
}]
[{
"$unionWith": {
"coll": <collection-name>,
"pipeline": [{
"$searchMeta": {
"<collector>": {
<collector-specification>
}
},

...
}]
}
}]

To see an example of $unionWith with $search, see the Atlas Search tutorial Run an Atlas Search $search Query Using $unionWith.要查看$unionWith$search的示例,请参阅Atlas search教程使用$unionwith运行Atlas search $search查询

Restrictions限制

Restrictions限制Description描述
transactions事务An aggregation pipeline cannot use $unionWith inside transactions.聚合管道不能在事务内部使用$unionWith
Sharded Collection分片集合If the $unionWith stage is part of the $lookup pipeline, the $unionWith coll cannot be sharded.如果$unionWith阶段是$lookup pipeline的一部分,则不能对$unionWith coll进行分片。
$outThe $unionWith pipeline cannot include the $out stage.$unionWith pipeline不能包括$out阶段。
$mergeThe $unionWith pipeline cannot include the $merge stage.$unionWith pipeline不能包含$merge阶段。

Examples实例

Create Sales Reports from the Union of Yearly Data Collections从年度数据集合联盟创建销售报告

The following examples use the $unionWith stage to combine data and return results from multiple collections. In these examples, each collection contains a year of sales data.以下示例使用$unionWith阶段组合数据并返回多个集合的结果。在这些示例中,每个集合都包含一年的销售数据。

Populate Sample Data填充示例数据

  1. Create a sales_2017 collection with the following documents:使用以下文档创建sales_2017集合:

    db.sales_2017.insertMany( [
    { store: "General Store", item: "Chocolates", quantity: 150 },
    { store: "ShopMart", item: "Chocolates", quantity: 50 },
    { store: "General Store", item: "Cookies", quantity: 100 },
    { store: "ShopMart", item: "Cookies", quantity: 120 },
    { store: "General Store", item: "Pie", quantity: 10 },
    { store: "ShopMart", item: "Pie", quantity: 5 }
    ] )
  2. Create a sales_2018 collection with the following documents:使用以下文档创建sales_2018集合:

    db.sales_2018.insertMany( [
    { store: "General Store", item: "Cheese", quantity: 30 },
    { store: "ShopMart", item: "Cheese", quantity: 50 },
    { store: "General Store", item: "Chocolates", quantity: 125 },
    { store: "ShopMart", item: "Chocolates", quantity: 150 },
    { store: "General Store", item: "Cookies", quantity: 200 },
    { store: "ShopMart", item: "Cookies", quantity: 100 },
    { store: "ShopMart", item: "Nuts", quantity: 100 },
    { store: "General Store", item: "Pie", quantity: 30 },
    { store: "ShopMart", item: "Pie", quantity: 25 }
    ] )
  3. Create a sales_2019 collection with the following documents:使用以下文档创建sales_2019集合:

    db.sales_2019.insertMany( [
    { store: "General Store", item: "Cheese", quantity: 50 },
    { store: "ShopMart", item: "Cheese", quantity: 20 },
    { store: "General Store", item: "Chocolates", quantity: 125 },
    { store: "ShopMart", item: "Chocolates", quantity: 150 },
    { store: "General Store", item: "Cookies", quantity: 200 },
    { store: "ShopMart", item: "Cookies", quantity: 100 },
    { store: "General Store", item: "Nuts", quantity: 80 },
    { store: "ShopMart", item: "Nuts", quantity: 30 },
    { store: "General Store", item: "Pie", quantity: 50 },
    { store: "ShopMart", item: "Pie", quantity: 75 }
    ] )
  4. Create a sales_2020 collection with the following documents:使用以下文档创建sales_2020集合:

    db.sales_2020.insertMany( [
    { store: "General Store", item: "Cheese", quantity: 100, },
    { store: "ShopMart", item: "Cheese", quantity: 100},
    { store: "General Store", item: "Chocolates", quantity: 200 },
    { store: "ShopMart", item: "Chocolates", quantity: 300 },
    { store: "General Store", item: "Cookies", quantity: 500 },
    { store: "ShopMart", item: "Cookies", quantity: 400 },
    { store: "General Store", item: "Nuts", quantity: 100 },
    { store: "ShopMart", item: "Nuts", quantity: 200 },
    { store: "General Store", item: "Pie", quantity: 100 },
    { store: "ShopMart", item: "Pie", quantity: 100 }
    ] )

Report 1: All Sales by Year and Stores and Items报告1:按年份、商店和项目列出的所有销售额

The following aggregation creates a yearly sales report that lists all sales by quarter and stores. 以下汇总创建了一个年度销售报告,其中按季度和门店列出了所有销售额。The pipeline uses $unionWith to combine documents from all four collections:管道使用$unionWith组合来自所有四个集合的文档:

db.sales_2017.aggregate( [
{ $set: { _id: "2017" } },
{ $unionWith: { coll: "sales_2018", pipeline: [ { $set: { _id: "2018" } } ] } },
{ $unionWith: { coll: "sales_2019", pipeline: [ { $set: { _id: "2019" } } ] } },
{ $unionWith: { coll: "sales_2020", pipeline: [ { $set: { _id: "2020" } } ] } },
{ $sort: { _id: 1, store: 1, item: 1 } }
] )

Specifically, the aggregation pipeline uses:具体而言,聚合管道使用:

  • A $set stage to update the _id field to contain the year.一个$set阶段,用于更新_id字段以包含年份。
  • A sequence of $unionWith stages to combine all documents from the four collections, each also using the $set stage on its documents.一个$unionWith阶段的序列,用于组合四个集合中的所有文档,每个集合还在其文档上使用$set阶段。
  • A $sort stage to sort by the _id (the year), the store, and item.一个$sort阶段,用于根据_id(年份)、storeitem进行排序。

Pipeline output:管道输出:

{ "_id" : "2017", "store" : "General Store", "item" : "Chocolates", "quantity" : 150 }
{ "_id" : "2017", "store" : "General Store", "item" : "Cookies", "quantity" : 100 }
{ "_id" : "2017", "store" : "General Store", "item" : "Pie", "quantity" : 10 }
{ "_id" : "2017", "store" : "ShopMart", "item" : "Chocolates", "quantity" : 50 }
{ "_id" : "2017", "store" : "ShopMart", "item" : "Cookies", "quantity" : 120 }
{ "_id" : "2017", "store" : "ShopMart", "item" : "Pie", "quantity" : 5 }
{ "_id" : "2018", "store" : "General Store", "item" : "Cheese", "quantity" : 30 }
{ "_id" : "2018", "store" : "General Store", "item" : "Chocolates", "quantity" : 125 }
{ "_id" : "2018", "store" : "General Store", "item" : "Cookies", "quantity" : 200 }
{ "_id" : "2018", "store" : "General Store", "item" : "Pie", "quantity" : 30 }
{ "_id" : "2018", "store" : "ShopMart", "item" : "Cheese", "quantity" : 50 }
{ "_id" : "2018", "store" : "ShopMart", "item" : "Chocolates", "quantity" : 150 }
{ "_id" : "2018", "store" : "ShopMart", "item" : "Cookies", "quantity" : 100 }
{ "_id" : "2018", "store" : "ShopMart", "item" : "Nuts", "quantity" : 100 }
{ "_id" : "2018", "store" : "ShopMart", "item" : "Pie", "quantity" : 25 }
{ "_id" : "2019", "store" : "General Store", "item" : "Cheese", "quantity" : 50 }
{ "_id" : "2019", "store" : "General Store", "item" : "Chocolates", "quantity" : 125 }
{ "_id" : "2019", "store" : "General Store", "item" : "Cookies", "quantity" : 200 }
{ "_id" : "2019", "store" : "General Store", "item" : "Nuts", "quantity" : 80 }
{ "_id" : "2019", "store" : "General Store", "item" : "Pie", "quantity" : 50 }
{ "_id" : "2019", "store" : "ShopMart", "item" : "Cheese", "quantity" : 20 }
{ "_id" : "2019", "store" : "ShopMart", "item" : "Chocolates", "quantity" : 150 }
{ "_id" : "2019", "store" : "ShopMart", "item" : "Cookies", "quantity" : 100 }
{ "_id" : "2019", "store" : "ShopMart", "item" : "Nuts", "quantity" : 30 }
{ "_id" : "2019", "store" : "ShopMart", "item" : "Pie", "quantity" : 75 }
{ "_id" : "2020", "store" : "General Store", "item" : "Cheese", "quantity" : 100 }
{ "_id" : "2020", "store" : "General Store", "item" : "Chocolates", "quantity" : 200 }
{ "_id" : "2020", "store" : "General Store", "item" : "Cookies", "quantity" : 500 }
{ "_id" : "2020", "store" : "General Store", "item" : "Nuts", "quantity" : 100 }
{ "_id" : "2020", "store" : "General Store", "item" : "Pie", "quantity" : 100 }
{ "_id" : "2020", "store" : "ShopMart", "item" : "Cheese", "quantity" : 100 }
{ "_id" : "2020", "store" : "ShopMart", "item" : "Chocolates", "quantity" : 300 }
{ "_id" : "2020", "store" : "ShopMart", "item" : "Cookies", "quantity" : 400 }
{ "_id" : "2020", "store" : "ShopMart", "item" : "Nuts", "quantity" : 200 }
{ "_id" : "2020", "store" : "ShopMart", "item" : "Pie", "quantity" : 100 }

Report 2: Aggregated Sales by Items报告2:按项目汇总的销售额

The following aggregation creates a sales report that lists the sales quantity per item. 以下聚合创建了一个销售报告,其中列出了每个项目的销售数量。The pipeline uses $unionWith to combine documents from all four years:管道使用$unionWith组合所有四年的文档:

db.sales_2017.aggregate( [
{ $unionWith: "sales_2018" },
{ $unionWith: "sales_2019" },
{ $unionWith: "sales_2020" },
{ $group: { _id: "$item", total: { $sum: "$quantity" } } },
{ $sort: { total: -1 } }
] )
  • The sequence of $unionWith stages retrieve documents from the specified collections into the pipeline:$unionWith阶段的序列将指定集合中的文档检索到管道中:
  • The $group stage groups by the item field and uses $sum to calculate the total sales quantity per item.$group阶段按item字段分组,并使用$sum计算每个物料的总销售数量。
  • The $sort stage orders the documents by descending total.$sort阶段按total降序排列文档。

Pipeline output:管道输出:

{ "_id" : "Cookies", "total" : 1720 }
{ "_id" : "Chocolates", "total" : 1250 }
{ "_id" : "Nuts", "total" : 510 }
{ "_id" : "Pie", "total" : 395 }
{ "_id" : "Cheese", "total" : 350 }