how to get data from 3 collections in mongodb using node js?

前端 未结 2 516
甜味超标
甜味超标 2021-01-19 21:21

I have the below collections in mongodb

db.orders.find()

{ \"_id\" : ObjectId(\"5cc69ad493297eade15bacb7\"), \"item\" : \"card\         


        
2条回答
  •  一整个雨季
    2021-01-19 21:46

    You have to change data-type of mobile_no in users_nippon collection from string to NumberLong otherwise $lookup will not work. After correcting it, now you can use below aggregation query to get your desired result in the same format you want.

    db.collection('users_nippon').aggregate([
    
            {
                $lookup: {
                  from: "orders",
                  localField: "mobile_no",
                  foreignField: "user_mob",
                  as: "orders_data"
                }
            },
            {
                $unwind: "$orders_data"
            },
            {
                $lookup: {
                    from: "items",
                    localField: "orders_data.item",
                    foreignField: "item",
                    as: "orders_data.items_data"
                }
            },
            {
                $unwind: "$orders_data.items_data"
            }
        ]).toArray(function(err, list) {
            if (err) throw err;
            console.log(JSON.stringify(list));
            res.send(JSON.stringify(list));
            });
    

    this is the tested and working solution.

提交回复
热议问题