MongoDB 聚合两个模型

MongoDB aggregate with two model

我有两个 collection, class collection 和学生 collection

class collection
{
    "_id" : "1999558581",
    "name" : "Class One",
},
{
    "_id" : "1999558582",
    "name" : "Class Two",
},
{
    "_id" : "1999558583",
    "name" : "Class Three",
}

student collection
{
    "_id" : "111111",
    "First name" : "",
    "Last name" : "",
    "gender" : "Male",
    "class" : "1999558581", //classObjectId
},
{
    "_id" : "111112",
    "First name" : "",
    "Last name" : "",
    "gender" : "Female",
    "class" : "1999558581", //classObjectId
},
{
    "_id" : "111113",
    "First name" : "",
    "Last name" : "",
    "gender" : "Male",
    "class" : "1999558582", //classObjectId
},
{
    "_id" : "111114",
    "First name" : "",
    "Last name" : "",
    "gender" : "Male",
    "class" : "1999558583", //classObjectId
},
{
    "_id" : "111115",
    "First name" : "",
    "Last name" : "",
    "gender" : "Female",
    "class" : "1999558581", //classObjectId
}

我想在 class 中获取按性别汇总并在 class collection 中获取姓名。

#这是我试过的

 const male = await models.Student.aggregate([
        { $match: { gender: "Male" } },
        { $group: { _id: "$class", count: { $sum: 1 } } },
    ]).exec();

#制作这个

             [
                {
                    "_id": "60703f09961728430c9656d1",
                    "count": 9
                },
                {
                    "_id": "60703f09961728430c",
                    "count": 4
                },
                 {
                    "_id": "60703f08430c9656d1",
                    "count": 13
                },
            ]

这个“_id”:“60703f09961728430c9656d1”,是来自classcollection的Id,所以我想获取与这个_id相关联的名字

               [
                {
                    "_id": "60703f09961728430c9656d1",
                     "name" : "Class One"
                    "count": 9
                },
                {
                    "_id": "60703f09961728430c",
                    "name" : "Class Two"
                    "count": 4
                },
                 {
                    "_id": "60703f08430c9656d1",
                    "name" : "Class Three"
                    "count": 13,
    
                },
            ]

您可以同时使用 $group 和 $lookup,这可能会解决您的问题。

const male = await models.Student.aggregate([
        { $match: { gender: "Male" } },
        { $group: { _id: "$class", count: { $sum: 1 } } },
        { $lookup: { from: "class", localField: "_id", foreignField: "_id", as: "class"}
    ]).exec()