【问题标题】:How to merge 2 collections with specific fields in mongodb, with aggregate & $lookup如何使用聚合和 $lookup 将 2 个集合与 mongodb 中的特定字段合并
【发布时间】:2021-08-15 03:25:18
【问题描述】:

我在使用聚合和 $lookup 时遇到问题。因此,非常感谢您的及时帮助。

假设我在同一个 mongoDB 中有这 2 个集合:

// collection1 (2 records, in this example):
{
  name: 'name1',
  city: 'city1'
}

{
  name: 'name2’,
  city: 'city2’
}

// collection2 (3 records, in this example):
{
  name: 'name1',
  education: ‘college’,
  occupation: ’engineer’,
  address: 'address1'
}

{
  name: 'name2’,
  education: ‘highschool’,
  occupation: ’manager’,
  address: 'address2'
}

{
  name: 'name3’,
  education: ‘highschool’,
  occupation: ’manager’,
  address: 'address3'
}

我想要一个最终集合,final_collection,像这样返回(名称字段用作索引):

{
  name: 'name1',
  city: 'city1'
  education: ‘college’,
  occupation: ’engineer’
}

{
  name: 'name2’,
  city: 'city2’
  education: ‘highschool’,
  occupation: ’manager’
}

本质上,只将“教育”和“职业”字段添加到 collection1 中,用于匹配的记录(姓名 1 和姓名 2)。

你能帮忙吗?非常感谢!

【问题讨论】:

    标签: mongodb aggregation-framework aggregation


    【解决方案1】:

    你可以$lookup 加入这两个集合

    • $lookup加入两个收藏
    • $addFields 添加新字段
    • $arrayElementAt 获取加入后的第一个元素。 $ifNull 防止数组中没有元素时发生 NPE

    这里是代码

    db.collection2.aggregate([
      {
        "$lookup": {
          "from": "collection1",
          "localField": "name",
          "foreignField": "name",
          "as": "join"
        }
      },
      {
        $addFields: {
          join: {
            $ifNull: [
              { "$arrayElemAt": [ "$join", 0 ] },
              []
            ]
          }
        }
      },
      {
        "$addFields": {
          "city": "$join.city",
          join: "$$REMOVE",
          address: "$$REMOVE"
        }
      }
    ])
    

    工作Mongo playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2021-04-11
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多