For example, my teacher collection documents look like:
{ _id: new ObjectId("64fee9b54273ac223441225"), teacherid: '64f1d72a4331bc8fc4c5930f', name: 'Jackly' }
and the users collection documents look like:
{ _id: new ObjectId("64f1d72a4331bc8fc4c5930f"), name: 'Mark' }
How can I get the name from users collection by the teacherid in the teacher collection? in MongoDB?
const studentData = await Teacher.aggregate([
{
$match: {
"_id": "64f1d72a4331bc8fc4c5930f"
}
},
{
$lookup: {
from: "users",
localField: "teacherid",
foreignField: "_id",
as: "student"
}
},
{
$unset: "name"
}
]);
3
Answers
It looks like you’re trying to use the MongoDB aggregation framework to perform a lookup between the "teacher" and "users" collections based on the "teacherid" field. However, there are a few issues with your current aggregation pipeline. Here’s the corrected version of your aggregation query:
Here’s an explanation of the changes made:
In the
$match
stage, you need to convert the_id
value to an ObjectId usingnew ObjectId()
to match the correct document in the "teacher" collection.After the
$lookup
stage, you have an array called "student" that contains the matching user document. To access the "name" field within the "student" subdocument, you need to use the$unwind
stage to destructure the array.Finally, you can use the
$project
stage to project only the "name" field from the "student" subdocument.Now,
studentData
should contain the "name" field from the "users" collection for the specified teacher ID in the "teacher" collection.Here is a quick fix solution
teacherid
to aObjectId
teacherid
as the match keytest ✅
the issue is that the two fields you are trying to compare are of 2 types. One is a string other is ObjectID. I would recommend to have both of them a single type (preferrably ObjectID) when storing so you don’t have to do these intermediate transformations.
however there are a couple of ways of doing this
teacherid
toObjectID
and then$lookup
. This will however have theteacherid
as an ObjectID in the queried result. If you dont want it that way you might have to do an$addFields
again and convert back to stringdemo
teacherid
to ObjectID in the lookup pipeline itself and compairingdemo
demo