MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Comment faire des jointures multiples entre deux collections dans mongodb en utilisant la fonction lambda ?

Veuillez vérifier ceci :

db.collection("user_posts").aggregate(
{ $match: {"userid" : uid}},
{ $unwind: '$like' },
{ $lookup: { from: "users", localField: "like.userid", foreignField: "_id", as: 
"users" }},
{ $group: {
    _id: "$_id",
    like: { $push: { $mergeObjects: ['$like', { $arrayElemAt: [ "$users", 0 ] } ]}},
    data: { $first: "$$ROOT" }
}},
{ $replaceRoot: { newRoot: { $mergeObjects: ['$data', { like: "$like"} ]} } },
{ $unwind: '$comment' },
{ $lookup: { from: "users", localField: "comment.userid", foreignField: "_id", as: 
 "users" }},
{ $group: {
    _id: "$_id",
        comment: { $push: { $mergeObjects: ['$comment', { $arrayElemAt: [ "$users", 0 
 ] } ]}},
        data: { $first: "$$ROOT" }
}},
{ $replaceRoot: { newRoot: { $mergeObjects: ['$data', { comment: "$comment"} ]} } },
{ $unwind: '$share' },
{ $lookup: { from: "users", localField: "share.userid", foreignField: "_id", as: 
"users" }},
{ $group: {
    _id: "$_id",
    share: { $push: { $mergeObjects: ['$share', { $arrayElemAt: [ "$users", 0 ] } 
]}},
    data: { $first: "$$ROOT" }
}},
{ $replaceRoot: { newRoot: { $mergeObjects: ['$data', { share: "$share"} ]} } },
{ $project: { users: 0 }}
)

vous obtiendrez une sortie, modifierez le nom des champs d'ajout/de suppression dans l'agrégation de projet selon vos besoins