当ForeignField在数组中时,如何在聚合中执行查找?

时间:2019-04-30 10:45:49

标签: mongodb mongodb-query aggregation-framework

我有两个收藏夹:

// users

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

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

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

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

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

我已经尝试使用此代码:

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

结果帐户数组中为空。

正确的方法是什么?

2 个答案:

答案 0 :(得分: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' }
])

答案 1 :(得分:0)

尝试一下

我认为情况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"
    }
}
])