MongoDB Join Query - localField Using _id for Matching Not Working
Scenario
Here's the situation - I have two documents: Document A
| _id | name |
|---|---|
| 6090acbd682e000028007e74 | jack |
| 6090acbd682e000028007e75 | rose |
Document B
| _id | a_id | state |
|---|---|---|
| 6787848807839043584 | 6090acbd682e000028007e74 | 1 |
| 6787848807839043585 | 6090acbd682e000028007e75 | 0 |
Then I need to join query Document A and Document B.
In MySQL we can do:
select * from A left join B on A._id=B.a_id
But in MongoDB we need to implement this through aggregate. Initially I wrote:
db.A.aggregate([
{$lookup:{
from: "B",
localField: "_id",
foreignField: "a_id",
as: "success_id"
}}])
Found there were no associated values at all.
Solution
Found a similar question on Stack Overflow. Turns out you need to add this to the query:
{
$addFields: { "_id": { "$toString": "$_id" } }
},

So the query becomes:
db.A.aggregate([
{
$addFields: { "_id": { "$toString": "$_id" } }
},
{$lookup:{
from: "B",
localField: "_id",
foreignField: "a_id",
as: "success_id"
}}])
This gives the joined result.