I have got two collections as follows:
Users:
_id | email
ObjectId("5ee493b0989d0f271cdc41c1") | joulie@gmail.com
ObjectId("5ee493b0989d0f271cdc41c3") | newelle@gmail.com
ObjectId("5ee493b0989d0f271cdc41c5") | john@gmail.com
ObjectId("5ee493b0989d0f271cdc41c7") | larry@gmail.com
Members:
group_id | user_id
ObjectId("5ee5e346fae4a21e28a81d91") | ObjectId("5ee493b0989d0f271cdc41c1")
ObjectId("5ee5e346fae4a21e28a81d92") | ObjectId("5ee493b0989d0f271cdc41c5")
I'm trying to search for email in Users collection and check if that the user associated with that email belongs to a specific group by comparing the supplied group_id parameter with group_id in Members collection.
For example, If the passed search parameters are: email: joulie, group_id: 5ee5e346fae4a21e28a81d91
Expected Output:
[
{ "email":"joulie@gmail.com",
"member_info": [
{"group_id":"5ee5e346fae4a21e28a81d91", "user_id":"5ee493b0989d0f271cdc41c1"}
]
}
]
For example, If the passed search parameters are:email: newelle, group_id: 5ee5e346fae4a21e28a81d91
Expected Output:
[
{ "email":"newelle@gmail.com",
"member_info": []
}
]
I hope the question makes sense.
I have followed a similar solution from this first one and this second one threads, but none of these seems to work for me.
Here's what I've tried so far:
db.users.aggregate([
{ "$match" : {email: { $regex: email +'.*'}}},
{
$lookup: {
from: "members",
let: { user_id: "$_id" },
pipeline: [
{ $match: {
$expr: { $and:
[
{ $in: [ group_id, "$group_id" ] },
{ $eq: [ "$$user_id", "$user_id" ] }
]
}
}}
],
as: "members"
}
}
])
Any help or guideline will be really appreciated. Thanks in advance!