Reputation: 261
I am trying to join 2 collections with eachother with MongoDB. It does not work however the way I want.. This is what I have now:
Trying to join these 2 collections
//Group collection
_id:ObjectId(5fa2d687c59139213cf8c081)
groupname: : chatting
//Peoplegroups collection
_id:5fa2d687c59139213cf8c082
groupid:5fa2d687c59139213cf8c081
user:PNZT4lvwQZPCWql6rWVEJHjt6Pe2
Using this nodejs code I am trying to get the query:
app.get("/groups/sync", (req, res) => {
db.collection("groups")
.aggregate([
{
$lookup: {
from: "peoplegroups",
localField: "groups_id",
foreignField: "groupid",
as: "User",
},
},
])
.toArray(function (err, data) {
if (err) throw res.status(500).send(err);
res.status(201).send(data);
});
});
Output:
[
{
"_id": "5fa2d687c59139213cf8c082",
"groupid": "5fa2d687c59139213cf8c081",
"user": "PNZT4lvwQZPCWql6rWVEJHjt6Pe2",
"__v": 0,
"User": [
{
"_id": "5fa2d687c59139213cf8c081",
"groupname": "rsr",
"__v": 0
},
{
"_id": "5fa2d689c59139213cf8c083",
"groupname": "rsrs",
"__v": 0
},
{
"_id": "5fa2d68ac59139213cf8c085",
"groupname": "easa",
"__v": 0
}
]
},
As you can see it returns all the peoplegroups fields instead of the matching groupid with the group_id. What is wrong??
Upvotes: 0
Views: 47
Reputation: 15177
First of all your $lookup
has a bad localField
. Following your schema should be _id
instead of groups_id
.
The second thing is, what are you trying to join?
Knowing an _id
get all peoplegroups
which groupid
is equal to _id
?
Or only group your peoplegroups
by the same groupid
?
To get the first one you need a $match
stage before the $lookup
like this:
db.group.aggregate([
{
"$match": {
"_id": 1
}
},
{
"$lookup": {
"from": "peoplegroups",
"localField": "_id",
"foreignField": "groupid",
"as": "User"
}
}
])
In this way you will get all users with groupid
equal to 1
.
Example here
But, the second option (following your query), will group different users. Look this example to know how works.
Upvotes: 1