筛选集合并将结果合并到 MongoDB 中的另一个集合中

Filter on collection and merge results in another collection in MongoDB

我正在使用 MongoDB 4.2.9 并且有以下要求:

集合 A

{ _id: "1",
  status: "Report",
  type: "Academy",
  rating: "Excellent",
  ReportNo: "A1"
},
{ _id: "2",
  status: "Open",
  type: "Academy",
  rating: "",
  ReportNo: ""
},
{ _id: "3",
  status: "Draft",
  type: "Academy",
  rating: "",
  ReportNo: ""
},
{ _id: "4",
  status: "Report",
  type: "Academy",
  rating: "Great",
  ReportNo: "A4"
}

集合 B

{ _id: "98",
  status: "Archived",
  type: "Academy",
  rating: "So So",
  ReportNo: "X2"
},
{ _id: "99",
  status: "Archived",
  type: "Academy",
  rating: "Great",
  ReportNo: "X1"
}

结果视图

{ _id: "1",
  status: "Report",
  type: "Academy",
  rating: "Excellent",
  ReportNo: "A1"
},
{ _id: "4",
  status: "Report",
  type: "Academy",
  rating: "Great",
  ReportNo: "A4"
},
{ _id: "98",
  status: "Archived",
  type: "Academy",
  rating: "So So",
  ReportNo: "X2"
},
{ _id: "99",
  status: "Archived",
  type: "Academy",
  rating: "Great",
  ReportNo: "X1"
}

我的目标是创建一个聚合视图,以便我可以过滤集合 'A' 中的状态值,然后将这些结果与集合 'B' 合并并显示在视图中 ?

我可以使用匹配调用过滤集合 'A',只是看不到如何将生成的文档合并到集合 'B'

根据我的理解,您的“合并”行为实际上是集合 A 和集合 B 的筛选视图的联合视图。

使用MongoDB v4.2,您可以使用$facet分别处理集合A和集合B。

  • 简单的对A进行过滤
  • 在 B
  • 上执行不相关 $lookup

整理结果并将它们合并在一起以获得您正在寻找的联合视图。

db.createCollection(
  "unionView",
  {
    "viewOn" : "A",
    "pipeline" : [
  {
    "$facet": {
      "A": [
        {
          "$match": {
            status: "Report"
          }
        }
      ],
      "B": [
        {
          $limit: 1
        },
        {
          "$lookup": {
            "from": "B",
            "pipeline": [],
            "as": "B"
          }
        },
        {
          $unwind: "$B"
        },
        {
          "$replaceRoot": {
            "newRoot": "$B"
          }
        }
      ]
    }
  },
  {
    $project: {
      all: {
        "$setUnion": [
          "$A",
          "$B"
        ]
      }
    }
  },
  {
    $unwind: "$all"
  },
  {
    "$replaceRoot": {
      "newRoot": "$all"
    }
  }
]
  }
)

这里是Mongo Playground供您参考。


使用 MongoDB v4.4+,您可以使用 $unionWith

创建视图
db.createCollection(
  "unionView",
  {
    "viewOn" : "A",
    "pipeline" : [
  {
    "$match": {
      status: "Report"
    }
  },
  {
    "$unionWith": {
      "coll": "B"
    }
  }
]
  }
)

这里是Mongo playground供您参考。