Skip to main content

MongoDB Join Query - localField Using _id for Matching Not Working

Scenario

Here's the situation - I have two documents: Document A

_idname
6090acbd682e000028007e74jack
6090acbd682e000028007e75rose

Document B

_ida_idstate
67878488078390435846090acbd682e000028007e741
67878488078390435856090acbd682e000028007e750

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" } }
},

image.png

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.