Reputation: 2807
MongoDb Aggregate lookup is not producing result while foreignField as _id.
I have two collections say users
and discussions
Sample users
Data:
[{
_id: 5f9c50dcfac1f091400225e3,
email: '[email protected]',
details: { fname: 'Peter Test', lname: 'Fulton' },
},
{
_id: 5fa432bfb91fab7db60c70eb,
email: '[email protected]',
details: { fname: 'Frodo', lname: 'Baggins' },
},
{
_id: 5fa8ec7d3ce22610e5d15190,
email: '[email protected]',
details: { fname: 'Tommy', lname: 'test' },
},
{
_id: 5fc38bb0b3683651be970180,
email: '[email protected]',
},
{
_id: 5fd2340cc443d155ab38383b,
email: '[email protected]',
details: { fname: 'Dexter', lname: 'Lab' },
}]
Sample discussions
data:
{_id: ObjectId("5fb2abd6b14fa5683979df58"),
tags: [ 'javascritp', 'css', 'html' ],
title: 'Why is this inline-block element pushed downward?',
post: 'Test Post',
learnerId: ObjectId("5f9c50dcfac1f091400225e3"),
}
Here '_id
' of users
is linked with 'learnerId
' of 'discussions
'.
My Aggregate query is like below.
db.users.aggregate([
{ $project: { "details.fname": 1, "details.lname":1,email:1, _id:1}},
{$lookup: {
from: "discussions",
localField: "learnerId",
foreignField: "_id",
as: "discussions"
}}
])
Here 'Peter Test'
with _id 5f9c50dcfac1f091400225e3
linked with discussions LeanerId
. But I expected discussions will populate in my result. My am seeing empty discussions array in all users collections.
[{
_id: 5f9c50dcfac1f091400225e3,
email: '[email protected]',
details: { fname: 'Peter Test', lname: 'Fulton' },
discussions: []
},
{
_id: 5fa432bfb91fab7db60c70eb,
email: '[email protected]',
details: { fname: 'Frodo', lname: 'Baggins' },
discussions: []
},
{
_id: 5fa8ec7d3ce22610e5d15190,
email: '[email protected]',
details: { fname: 'Tommy', lname: 'test' },
discussions: []
},
{
_id: 5fc38bb0b3683651be970180,
email: '[email protected]',
discussions: []
},
{
_id: 5fd2340cc443d155ab38383b,
email: '[email protected]',
details: { fname: 'Dexter', lname: 'Lab' },
discussions: []
}]
Can you point out what wrong in my aggregate query here?
Upvotes: 1
Views: 1290
Reputation: 8894
You have mismatched the localField and foreignField
db.users.aggregate([
{
$project: {
"details.fname": 1,
"details.lname": 1,
email: 1,
_id: 1
}
},
{
$lookup: {
from: "discussions",
localField: "_id",
foreignField: "learnerId",
as: "discussions"
}
}
])
Working Mongo playground
Upvotes: 1