There are two sets:
A set of “user information”;
“Articles” are stored in set B;
Each article in collection b has a comment field as follows:
comment:[{
uid:"59ffd1966e39780ae3fd99c3",
Message:' Comments'
},{
uid:"59ffd269fbcba4346517c098",
Message:' Comments'
},{
uid:"59ffd278fbcba4346517c099",
Message:' Comments'
}]
How to use uid to associate the user information in set A when querying article comments? The expected results are as follows:
comment:[{
Username: "User Name",
......
Message:' Comments'
},{
Username: "User Name",
......
Message:' Comments'
},{
Username: "User Name",
......
Message:' Comments'
}]
It is not desirable to find out and reinsert the data of set A when inserting data into set B, thus there is data redundancy. . . . ;
Only the user ID and no other user information are put in the B set.
Looking through MONGODB MANUAL, I could not find it. . . .
db.b.aggregate([
{$unwind: "$comment"},
{
$lookup:
{
from: "A",
localField: "comment.uid",
foreignField: "uid",
as: "guest"
}
},
{$group : {_id:"$title",comments:{$push:"$comment"}}
]);
In fact, the only results returned are title and comments, and all other related fields are missing. . . .
Solve!
db.b.aggregate([ {$unwind: "$comment"}, { $lookup: { from: "A", localField: "comment.uid", foreignField: "uid", as: "guest" } }, {$ group: {_ id: "$ title", fulldoc: {$ push: "$ $ root"}}/<-put the entire document in ]);
Although this can achieve your goal, it is suggested that you still consider redundancy. Data consistency here is not so important.
In addition$lookup
Although it can solve the problem, its performance is not very good, and it does not support Sharding, so it should be used with caution.