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

前端 未结 2 517
甜味超标
甜味超标 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.

    0 讨论(0)
  • 2021-01-19 21:50

    There are 2 issues in your query:

    1. The field user_mob (orders schema) is a Number while mobile_no (user_nippon schema) is a String therefore the lookup cannot be made. You might want to use the same type for those fields.

    2. The second lookup is incorrect. the first lookup and unwind returns your item element inside the orders_data element so the localField of this lookup should be changed to: orders_data.item

    So after you change both user_mob and mobile_no to have matching types your query would look like this:

    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: "items_data"
                    }
                },
                {
                    $unwind: "$items_data"
                }
            ]).toArray(function(err, list) {
                if (err) throw err;
                console.log(JSON.stringify(list));
                res.send(JSON.stringify(list));
                });
    
    
    0 讨论(0)
提交回复
热议问题