MongoDB: Combine data from multiple collections into one..how?

后端 未结 11 1259
余生分开走
余生分开走 2020-11-22 06:44

How can I (in MongoDB) combine data from multiple collections into one collection?

Can I use map-reduce and if so then how?

I would greatly appreciate some

11条回答
  •  萌比男神i
    2020-11-22 07:25

    Very basic example with $lookup.

    db.getCollection('users').aggregate([
        {
            $lookup: {
                from: "userinfo",
                localField: "userId",
                foreignField: "userId",
                as: "userInfoData"
            }
        },
        {
            $lookup: {
                from: "userrole",
                localField: "userId",
                foreignField: "userId",
                as: "userRoleData"
            }
        },
        { $unwind: { path: "$userInfoData", preserveNullAndEmptyArrays: true }},
        { $unwind: { path: "$userRoleData", preserveNullAndEmptyArrays: true }}
    ])
    

    Here is used

     { $unwind: { path: "$userInfoData", preserveNullAndEmptyArrays: true }}, 
     { $unwind: { path: "$userRoleData", preserveNullAndEmptyArrays: true }}
    

    Instead of

    { $unwind:"$userRoleData"} 
    { $unwind:"$userRoleData"}
    

    Because { $unwind:"$userRoleData"} this will return empty or 0 result if no matching record found with $lookup.

提交回复
热议问题