While trying to use lookup
in 2nd level, getting an empty array instead of an object.
I have 3 collections,
1. registration
2. bus
3. operator
Here, registration
contains busId
, and the bus
contains the operatorId
.
I first populate the bus
using the busId
of registration
.
Then with the populated bus
try to populate the operator
.
Documents of registration collection:
{ "_id": "1", "busId": "1" }
{ "_id": "2", "busId": "2" }
Documents of bus collection:
{ "_id": "1", "operatorId": "1", "name": "bus 01" }
{ "_id": "2", "operatorId": "2", "name": "bus 02" }
Documents of operator collection:
{ "_id": "1", "name": "operator 01" }
{ "_id": "2", "name": "operator 02" }
My expected result:
[
{
_id: '1',
busId: '1',
busInfo: { _id: '1', operatorId: '1', name: 'bus 01' },
operatorInfo: { _id: '1', name: 'operator 01' }
},
{
_id: '2',
busId: '2',
busInfo: { _id: '2', operatorId: '2', name: 'bus 02' },
operatorInfo: { '_id': '2', name: 'operator 02' }
}
]
What I tried this far:
I am using the following aggregation:
db.collection('registration').aggregate([
{
$lookup: {
from: 'bus',
localField: 'busId',
foreignField: '_id',
as: 'busInfo'
}
},
{ $unwind: '$busInfo' },
{
$lookup: {
from: 'operator',
localField: 'busInfo.operatorId',
foreignField: '_id',
as: 'operatorInfo'
}
}
]);
And getting the empty operator list.
[
{
_id: '1',
busId: '1',
busInfo: { _id: '1', operatorId: '1', name: 'bus 01' },
operatorInfo: []
},
{
_id: '2',
busId: '2',
busInfo: { _id: '2', operatorId: '2', name: 'bus 02' },
operatorInfo: []
}
]
This result has the empty operatorInfo
Array. But I need the operatorInfo
object.
The first lookup
is working fine. But after getting bus
from the busId
, I need to get the operator
details of the operatorId
. operatorId
is inside the bus
.