如何通过聚合加入3个集合?

时间:2018-10-04 13:36:08

标签: node.js mongodb mongoose aggregation-framework

这是我的结构

国家/地区

[
    {
        "studentid": [
            "5bb482fdac231f1354c47aab"
        ],
        "_id": "5bb672fb92c98117d004c733",
        "name": "china",
        "__v": 0
    }
]

用户

[
    {
        "books": [
            "5bb657ea05bf6d0ef096e529",
            "5bb6580d05bf6d0ef096e52a"
        ],
        "_id": "5bb482fdac231f1354c47aab",
        "firstName": "will",
        "lastName": "smith",
        "email": "user3@gmail.com",
        "address": "rajkot",
        "salary": 5000,
        "department": "electrical",
        "__v": 0
    }
]

[
    {
        "_id": "5bb657ea05bf6d0ef096e529",
        "name": "book 1",
        "price": 100,
        "pages": 200,
        "__v": 0
    }
]

现在我正尝试将每个数组明智地加入这3个集合

这是我尝试过的代码

CountryModel.aggregate([
    { $match: { name: country } },
    {
        $lookup: {
            from: UserModel.collection.name,
            let: { student_id: "_id" },
            pipeline: [
                { "$match": { "_id": "$student_id" } },
                {
                    $lookup: {
                        from: UserModel.collection.name,
                        let: { book_id: "$books" },
                            pipeline: [
                                {
                                    $lookup: {
                                        from: BookModel.collection.name,
                                        let: { bookid: "$_id" },
                                        pipeline: [
                                            { "$match": { "$expr": { "$in": ["$book_id", "$bookid"] } } },
                                        ],
                                        as: "more"
                                    }
                                }
                            ],
                            as: "books"
                        }
                    }
                ],
                as: "studentid"
            },
        },
    ])

有人可以告诉我我做错了吗?

0 个答案:

没有答案
相关问题