MongoDB聚合:$unionWith

$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" },
])

下面的聚合合并了聚合supplierswarehouse的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管道的一部分,则$unionWithcoll被分片。例如,在下面的聚合操作中,不能对inventory_q1集合进行分片:

db.suppliers.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值