$unionWith
聚合阶段执行两个集合的合并,将两个集合的管道结果合并到一个结果集传送到下一个阶段。合并后的结果文档的顺序是不确定的。
语法
{
$unionWith: {
coll: "<collection>", pipeline: [ <stage1>, ... ] } }
要包含集合的所有文档不进行任何处理,可以使用简化形式:
{
$unionWith: "<collection>" } // 包含指定集合的所有文档
使用
参数字段:
字段 | 描述 |
---|---|
coll |
希望在结果集中包含的集合或视图管道的结果 |
pipeline |
可选,应用于coll 的聚合管道[<stage1>, <stage2>, ....] ,聚合管道不能包含$out 和$merge 阶段。从v6.0开始,管道可以在第一个阶段包含$search 阶段 |
$unionWith
操作等价于下面的SQL语句:
SELECT *
FROM Collection1
WHERE ...
UNION ALL
SELECT *
FROM Collection2
WHERE ...
重复的结果
前一阶段的合并结果和$unionWith
阶段的合并结果可能包含重复结果。例如,创建一个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" },
])
下面的聚合合并了聚合suppliers
和warehouse
的state’字段投影结果。
db.suppliers.aggregate([
{
$project: {
state: 1, _id: 0 } },
{
$unionWith: {
coll: "warehouses", pipeline: [ {
$project: {
state: 1, _id: 0 } } ]} }
])
结果包含重复的文档
{
"state" : "Texas" }
{
"state" : "Colorado" }
{
"state" : "Rhode Island" }
{
"state" : "California" }
{
"state" : "Colorado" }
{
"state" : "Florida" }
要要去除重复,可以加个$group
阶段,按照state
字段分组:
db.suppliers.aggregate([
{
$project: {
state: 1, _id: 0 } },
{
$unionWith: {
coll: "warehouses", pipeline: [ {
$project: {
state: 1, _id: 0 } } ]} },
{
$group: {
_id: "$state" } }
])
这样结果就没有重复的文档了:
{
"_id" : "California" }
{
"_id" : "Texas" }
{
"_id" : "Florida" }
{
"_id" : "Colorado" }
{
"_id" : "Rhode Island" }
$unionWith 分片集合
如果$unionWith
阶段是$lookup
管道的一部分,则$unionWith
的coll
被分片。例如,在下面的聚合操作中,不能对inventory_q1
集合进行分片:
db.suppliers.