【问题标题】:How to perform lookup in aggregation when foreignField is in array?当foreignField在数组中时如何在聚合中执行查找?
【发布时间】:2019-04-30 19:52:40
【问题描述】:

我有两个收藏:

// users

{
    _id: "5cc7c8773861275845167f7a",
    name: "John",
    accounts: [
        { 
            "_id": "5cc7c8773861275845167f76", 
            "name": "Name1", 
        },
        { 
            "_id": "5cc7c8773861275845167f77", 
            "name": "Name2", 
        }
    ]
}
// transactions

{
    "_id": "5cc7c8773861275845167f75",
    "_account": "5cc7c8773861275845167f76",
}

使用查找,我想用 users.accounts 数组中的相应元素填充交易集合中的 _account 字段。

所以,我希望最终结果为:

{
    "_id": "5cc7c8773861275845167f75",
    "_account": { 
        "_id": "5cc7c8773861275845167f76", 
        "name": "Name1", 
    },
}

我已经尝试过使用此代码:

db.transactions.aggregate([
   {
     $lookup:
       {
         from: "users.accounts",
         localField: "_account",
         foreignField: "_id",
         as: "account"
       }
  }
])

结果帐户数组为空。

正确的做法是什么?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以将以下聚合与 mongodb 3.6 及更高版本一起使用

    db.transactions.aggregate([
      { "$lookup": {
        "from": "users",
        "let": { "account": "$_account" },
        "pipeline": [
          { "$match": { "$expr": { "$in": ["$$account", "$accounts._id"] } } },
          { "$unwind": "$accounts" },
          { "$match": { "$expr": { "$eq": ["$$account", "$accounts._id"] } } }
        ],
        "as": "_account"
      }},
      { '$unwind': '$_account' }
    ])
    

    【讨论】:

      【解决方案2】:

      试试这个

      我认为案例 1 更好。

      1)-

      db.getCollection('transactions').aggregate([
      {
      $lookup:{
      from:"user",
      localField:"_account",
      foreignField:"accounts._id",
      as:"trans"
      }    
      },
      {
      $unwind:{
          path:"$trans",
          preserveNullAndEmptyArrays:true
          }
      },
      {
      $unwind:{
          path:"$trans.accounts",
          preserveNullAndEmptyArrays:true
          }
      },
      {$match: {$expr: {$eq: ["$trans.accounts._id", "$_account"]}}},
      {$project:{
      _id:"$_id",
      _account:"$trans.accounts"
      }}
      ])
      

      2)-

      db.getCollection('users').aggregate([
      {
      $unwind:{
      path:"$accounts",
      preserveNullAndEmptyArrays:true
      }    
      },
      {
      $lookup:
      {
       from: "transactions",
       localField: "accounts._id",
       foreignField: "_account",
       as: "trans"
      }
      },
      {$unwind:"$trans"},
      {
      $project:{
          _id:"$trans._id",
          _account:"$accounts"
          }
      }
      ])
      

      【讨论】:

      • 哪个集合是测试的?交易还是用户?
      • 已更新。测试意味着用户
      猜你喜欢
      • 1970-01-01
      • 2020-02-20
      • 2021-01-08
      • 2018-11-27
      • 1970-01-01
      • 2022-12-05
      • 2021-05-06
      • 2019-06-29
      • 2020-12-18
      相关资源
      最近更新 更多