How do i join user with company that are primary to the user? see below for sample the data.
db.companies.insert([
{ "_id" : 4, "name" : "CompanyABC"},
{ "_id" : 5, "name" : "CompanyLMN"},
{ "_id" : 6, "name" : "CompanyXYZ"},
])
db.user.insert([
{
"_id": 1,
"name": "john",
"companies": [
{
"_id": 4,
"primary": true
},
{
"_id": 5,
"primary": false
},
{
"_id": 6,
"primary": false
}
]
},
"_id": 2,
"name": "jane",
"companies": [
{
"_id": 4,
"primary": false
},
{
"_id": 5,
"primary": true
},
{
"_id": 6,
"primary": false
}
]
},
])
I tried doing this below but it returned empty.
db.users.aggregate( [{
'$lookup' => [
'from' => 'companies',
'let' => ['company' => '$companies'],
'pipeline' => [
[
'$match' => [
'$expr' => [
'$and' => [
['$eq' => ['$_id', '$$company._id']],
['$eq' => ['$$company.primary', true]]
]
]
]
]
],
'as' => 'actualCompanies',
]
}]