【问题标题】:How to use mongodb aggregate to enrich objects with $lookup?如何使用 mongodb 聚合通过 $lookup 来丰富对象?
【发布时间】:2021-09-14 13:31:25
【问题描述】:

我正在使用 Pymongo 针对我们的 Mongodb 运行聚合管道。

我有以下收藏:

用户

{
  _id: 1,
  name: 'John Doe',
  age: 30
},
{
  _id: 2,
  name: 'Jane Doe',
  age: 20
}

位置

{
  _id: 10,
  name: 'Miami'
},
{
  _id: 20,
  name: 'Orlando'
}

联系人

{
  _id: 100,
  contacts: [
    {
      user_id: 1,
      location_id: 10,
    },
    {
      user_id: 2,
      location_id: 20,
    }
  ]
}

作为聚合管道的结果,我需要:

{
  _id: 100,
  contacts: [
    {
      user_id: 1,
      user_name: 'John Doe',
      user_age: 30,
      location_id: 10,
      location_name: 'Miami'
    },
    {
      user_id: 2,
      user_name: 'Jane Doe',
      user_age: 20,
      location_id: 20,
      location_name: 'Orlando'
    }
  ]
}

我尝试了一些使用“$lookup”的查询,但我只是得到一个新数组,而不是将值放在同一个数组/对象中。

我怎样才能得到想要的结果?

【问题讨论】:

    标签: python mongodb mongodb-query aggregation-framework pymongo


    【解决方案1】:

    您可以使用此聚合查询:

    • 首先$unwind 解构数组并获取要加入的值
    • 然后两个$lookup 连接值并创建数组userslocations
    • 由于使用了_id,因此您想要的数组中的值是第一个(它应该只有一个值,但如果存在多个值,则应该是重复值),因此您可以使用$arrayElemAt
    • 然后$project获取你想要的字段名。
    • $group 重新组合这些值。
    db.contacts.aggregate([
      {
        "$unwind": "$contacts"
      },
      {
        "$lookup": {
          "from": "users",
          "localField": "contacts.user_id",
          "foreignField": "_id",
          "as": "users"
        }
      },
      {
        "$lookup": {
          "from": "locations",
          "localField": "contacts.location_id",
          "foreignField": "_id",
          "as": "locations"
        }
      },
      {
        "$set": {
          "users": {
            "$arrayElemAt": [
              "$users",
              0
            ]
          },
          "locations": {
            "$arrayElemAt": [
              "$locations",
              0
            ]
          }
        }
      },
      {
        "$project": {
          "contacts": {
            "user_id": 1,
            "location_id": 1,
            "user_name": "$users.name",
            "user_age": "$users.age",
            "location_name": "$locations.name"
          }
        }
      },
      {
        "$group": {
          "_id": "$_id",
          "contacts": {
            "$push": "$contacts"
          }
        }
      }
    ])
    

    例如here

    【讨论】:

      猜你喜欢
      • 2016-07-12
      • 2022-01-05
      • 2016-10-08
      • 2020-07-12
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多