1

I have two collections:

// users

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

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

Using lookup I want to populate _account field in transactions collection with respective element from users.accounts array.

So, I want the final result as:

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

I have already tried using this code:

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

In the result account array comes as empty.

What is the correct way to do it ?

2 Answers 2

1

You can use below aggregation with mongodb 3.6 and above

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' }
])
Sign up to request clarification or add additional context in comments.

Comments

0

Try with this

I think case 1 is better.

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"
    }
}
])

2 Comments

Which collection is test? Transactions or Users ?
Updated. Test means users

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.