如何加入 parent 与 child 相同的 collection mongodb

how join parent with child of the same collection mongodb

我有以下 collection 称为 servicebyAff,其中引用了 parent collection

{
    "_id" : ObjectId("53ed7efca75ca1a5248a281a"),
    "category" : {_id, ref: category},
    "service" : {_id, ref: service}
}

我使用 $lookup 加入 collection 结果是这样

{
    "_id": ObjectId("5d4fb125ec8bb5af826935f1"),
    "category": {
        "_id": ObjectId("5d4fb125ec8bb5af826935f1"),
        "active": true,
        "enabled": false,
        "name": {
            "en": "General Medicine",
            "other": "xxx"
        },
      "description": {
            "en": "Is a General Medicine",
            "other": "xxx"
        },
        "parentCategory": [
            "5dd095d860c43279e76e8d06"
        ]
    },
    "service":  [
        {
            "_id": "5ce520370fc47e2d0edc4411",
            "active": true,
            "enabled": true,
            "affiliateType": [
                "5d242feb3555ec2b76e86bce"
            ],
            "name": {
                "en": "Laboratory Tests",
                "other": "xxx"
            },
            "description": {
                "en": "Laboratory Tesrs",
                "es": "xxx"
            },
            "createdAt": "2019-05-22T10:11:03.945Z",
            "updatedAt": "2019-12-30T21:55:03.569Z",
            "__v": 0,
            "isAppointment": false,
            "atHome": true
        }
    ]
}

因此,从类别 (collection) 参考中,我想将 parent 分组到此 collection 的 children 中。通过以下方式:

{
    "_id": ObjectId("5d4fb125ec8bb5af826935f1"),
    "category": {
        "_id": ObjectId("5d4fb125ec8bb5af826935f1"),
        "active": true,
        "enabled": false,
        "name": {
            "en": "General Medicine",
            "other": "xxx"
        },
        "description": {
            "en": "Is a General Medicine",
            "other": "xxx"
        },
        "parentCategory": {
            "_id": ObjectId("5d4fb125ec8bb5af826935f1"),
            "active": true,
            "enabled": false,
            "name": {
                "en": "Parents of General Medicine",
                "other": "xxx"
            },
            "description": {
                "en": "Parents General Medicine",
                "other": "xxx"
            }
        }
    },
    "service": [
        {
            "_id": "5ce520370fc47e2d0edc4411",
            "active": true,
            "enabled": true,
            "affiliateType": [
                "5d242feb3555ec2b76e86bce"
            ],
            "name": {
                "en": "Laboratory Tests",
                "other": "xxx"
            },
            "description": {
                "en": "Laboratory Tesrs",
                "es": "xxx"
            },
            "createdAt": "2019-05-22T10:11:03.945Z",
            "updatedAt": "2019-12-30T21:55:03.569Z",
            "__v": 0,
            "isAppointment": false,
            "atHome": true
        }
    ]
}

我需要一个包含所有 parent 元素的结果。那是我的代码

export const categoriesAtHome = async (req: Request & any, res: Response, next: NextFunction) => {
    try {
        // ?=idService="xxx"&idCategories=""&enable=true
        //        {$or: [{service: {ObjectId('5ce520370fc47e2d0edc4411')}}], enabled: true}
        const { affiliateId } = req.params;
        const affiliateObjectId = Types.ObjectId(affiliateId);

        // const sort: any = { "createdAt": -1 };

        // const categoriesByAtHome = await Category.find({
        //     service: idServiceObjectId,
        //     enabled: true,
        // }).populate("service").populate("subCategory").populate("menu").sort(sort).lean().exec();

        const categoryConditions = {
            enabled: true,
            active: true
        };

        const data = await ServicesByAffiliate.aggregate([{
            $match: { affiliate: affiliateObjectId, enabled: true }
        }, {
            $lookup: {
                from: "services",
                localField: "service",
                foreignField: "_id",
                as: "service"
            }
        },
        {
            $unwind: "$service"
        },
        {
            $lookup: {
                from: "categories",
                localField: "category",
                foreignField: "_id",
                as: "category",
            }
        },
        {
            $project: {
                _id: { $ifNull: ["$parentCategory", "$category.parentCategory"] },
                parent: '$category',
                parentCategory: { $ifNull: ["$parentCategory", false] }
            }
        },
        // {
        //     $group: {
        //         _id: "$_id",
        //         name: { $min: { $cond: ["$parentCategory", false, "$name"] } },
        //         childCount: {
        //             $sum: {
        //                 $cond: [
        //                     "$parentCategory",
        //                     1,
        //                     0
        //                 ]
        //             }
        //         },
        //         lastContent: { $last: "$description" }
        //     }
        // },


            // _id?: any;
            // // code: any;
            // name: any;
            // parentCategory?: any;
            // description: any;
            // active?: boolean;
            // enabled?: boolean;
            // service: ServiceModel[];
            // updatedBy?: UserModel;
            // menu?: MenuModel[];
            // {
            //     $project: {
            //         _id: { $cond: ['$parentCategory', '$parentCategory', '$category.parentCategory'] },
            //         name: 1,
            //         parent: '$category',
            //         parentCategory: { $ifNull: ['$parentCategory', false] },
            //     },
            // },

            // {
            //     $group: {
            //         _id: "$_id",
            //         parentCategory: { 
            //             $addToSet: {
            //                 $arrayElemAt: [ "$" ]
            //             }
            //          }

            //     }
            // }

            // {
            //     $addField: {
            //         group: {
            //             $filter: {
            //                 input: "$category",
            //                 as: "category",
            //                 cond: { 
            //                     $and: [
            //                         {
            //                             $eq: ["$$parentCategory"]
            //                         }
            //                     ]
            //                 }
            //             }
            //         }
            //     }
            // }

            // {
            //     $lookup: {
            //         from: "categories",
            //         let: { id: "$_id" },
            //         pipeline: [{
            //             $match: {
            //                 ...categoryConditions
            //             }
            //         }],
            //         as: "category"
            //     }
            // },
            // {
            //     $project: {
            //         category: { $arrayElemAt: ["$parentCategory", 0] }
            //     }
            // }



            // {
            //     $graphLookup: {
            //         restrictSearchWithMatch: categoryConditions,
            //         from: "categories",
            //         startWith: "$_id",
            //         connectFromField: "_id",
            //         connectToField: "parentCategory",
            //         depthField: "depth",
            //         as: "items"
            //     }
            // }
        ]);

        res.status(200).json({
            data: data
        });


    } catch (error) {
        res.status(500).json({ error: true, message: error.toString() });
    }

};

请帮帮我!我已经尝试了将近八个小时,我需要帮助

只需要在查询的末尾为 parentCategory 添加一个 $lookup

  {
    $lookup: {
      from: "categories",
      localField: "category.parentCategory",
      foreignField: "_id",
      as: "category.parentCategory"
    }
  }

没问题,可以在$addFields,

中使用$first运算符代替$unwind阶段
  // $lookup with service
  // $lookup with category
  {
    $addFields: {
      service: { $first: "$service" },
      category: { $first: "$category" }
    }
  },
  // $lookup with category for parent category

Playground

中添加的最终查询