I have been trying to join two collection in MongoDb using the aggregate function but it seems it’s not working for me, When I run api using lookup it show the me empty collection [],
I have tried with the following.
db.student.aggregate([
{
"$match": {
_id: "63c4c245188267e988d690e2"
},
},
{
"$lookup": {
"from": "wall",
"localField": "_user",
"foreignField": "_id",
"as": "wallpost"
}
}
])
Result:
Here is the result i m getting after lookup 🙁
[
{
"_id": "63c4c245188267e988d690e2",
"hereFor": [
{
"mainTag": "study",
"subtag": [
"studybuddy",
"findtutor"
]
}
],
"lastName": "Kumar",
"name": "Kamal",
"profilePicture": [
"https://airustudentimages.s3.ca-central-1.amazonaws.com/1673588594404-ba7777ef676f439f86aa612e8be67fd9"
],
"wallpost": []
}
]
Collections
Collection i m using in the query.
Student
student: [
{
"_id": "63c4c245188267e988d690e2",
"name": "Kamal",
"lastName": "Kumar",
"profilePicture": [
"https://airustudentimages.s3.ca-central-1.amazonaws.com/1673588594404-ba7777ef676f439f86aa612e8be67fd9"
],
"hereFor": [
{
"mainTag": "study",
"subtag": [
"studybuddy",
"findtutor"
]
}
],
},
{
"_id": "63c3965c201a1d738ab6867e",
"name": "Suraksha",
"lastName": "Singh",
"profilePicture": [
"https://airustudentimages.s3.ca-central-1.amazonaws.com/1673762449670-a8bdf9b9b0faf3ad84e0a5bc76e32fb8"
],
"hereFor": [
{
"mainTag": "study",
"subtag": [
"studybuddy",
"findtutor"
]
}
],
}
],
Wall
"wall": [
{
"_id": "63c4c92a188267e988d690e3",
"_user": "63c3965c201a1d738ab6867e",
"isSponsered": false,
"description": "Hello test case ",
"tag": {
"mainTag": "hostels"
},
"createdAt": "1673766717308",
"updatedAt": "1673766717308",
},
{
"_id": "63c4cc2b188267e988d690e5",
"_user": "63c3965c201a1d738ab6867e",
"isSponsered": false,
"description": "Hello test case 22 ",
"tag": {
"mainTag": "hostels"
},
"createdAt": "1673766717308",
"updatedAt": "1673766717308",
},
],
Have a look at https://mongoplayground.net/p/2moDXi3lygL
2
Answers
You mix up the
localField
andforeignField
.From Equality Match with a Single Join Condition:
It should be:
Demo @ Mongo Playgound
Your query is on
Student
collection. So thelocalField
should be_id
and and theforeignField
should be_user
(fromwall
collection).Then it works fine.
https://mongoplayground.net/p/r1JeQIlM7AA