mongoose mongoDB -如何在每个文档中只保留来自$lookup的匹配数据

xj3cbfub  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(146)

我想只保留计数中的数据,这些数据将与每个单独文档的父ID相匹配。

学生架构

const StudentSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please Provide Name"],
      maxlength: 100,
      minlength: 2,
    },
    email: {
      type: String,
      required: [true, "Please Provide Email"],
      match: [
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        "Please Provide a Valid Email",
      ],
      unique: true,
    },
    number: {
      type: String,
      required: [true, "Please Provide Number"],
      match: [
        /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/,
        "Please Provide a Valid Number",
      ],
      unique: true,
    },
    rollNumber: {
      type: Number,
      required: [true, "Please Provide Roll Number"],
      maxlength: 5,
    },
    departmentID: {
      type: mongoose.Types.ObjectId,
      ref: "Department",
      required: [true, "Please Provide departmentID"],
    },
    classID: {
      type: mongoose.Types.ObjectId,
      ref: "Class",
      required: [true, "Please Provide classID"],
    },
    position: {
      type: String,
      required: [true, "Please Provide Position"],
      enum: ["Student"],
      default: "Student",
    },
    password: {
      type: String,
      required: [true, "Please Provide Password"],
      minlength: 6,
    },
  },
  { timestamps: true }
);

考勤模式

const AttendanceSchema = new Schema(
  {
    date: {
      type: String,
      required: [true, "Please Provide Date"],
      maxlength: 15,
      minlength: 5,
    },
    subjectID: {
      type: mongoose.Types.ObjectId,
      ref: "Subject",
      required: [true, "Please Provide Subject"],
    },
    studentID: {
      type: mongoose.Types.ObjectId,
      ref: "Student",
      required: [true, "Please Provide Student"],
    },
    teacherID: {
      type: mongoose.Types.ObjectId,
      ref: "Faculty",
      required: [true, "Please Provide Teacher"],
    },
    classID: {
      type: mongoose.Types.ObjectId,
      ref: "Class",
      required: [true, "Please Provide Class"],
    },
    departmentID: {
      type: mongoose.Types.ObjectId,
      ref: "Department",
      required: [true, "Please Provide Department"],
    },
  },

  { timestamps: true }
);

我的查询

const data = await StudentSchema.aggregate([
      { $match: { classID: mongoose.Types.ObjectId(`${req.params.id}`) } },
      {
        $lookup: {
          from: "attendances",
          pipeline: [
            {
              $match: {
                subjectID: mongoose.Types.ObjectId(`${req.params.Sid}`),
              },
            },
            { $group: { _id: "$studentID", count: { $sum: 1 } } },
          ],
          as: "counts",
        },
      },
    ]);

这是我从这个查询中得到的数据:

{
    "data": [
        {
            "_id": "63677d2960fa65e95aef5e95",
            "name": "Lavannya Urkande",
            "email": "lavannya@gmail.com",
            "number": "9130354519",
            "rollNumber": 201,
            "departmentID": "6365531fdc02a121ffeed944",
            "classID": "636554e8dc02a121ffeed982",
            "position": "Student",
            "password": "$2a$10$mqysVgtIGrYbvMGtHE2vbu0z5g05BlwJizcc.CfWMld78VPrnvcrO",
            "createdAt": "2022-11-06T09:23:53.803Z",
            "updatedAt": "2022-11-06T09:23:53.803Z",
            "__v": 0,
            "counts": [
                {
                    "_id": "6367819d60fa65e95aef5ea7",
                    "count": 2,
                },
                {
                    "_id": "63677d2960fa65e95aef5e95",
                    "count": 3,
                }
            ]
        },
        {
            "_id": "6367819d60fa65e95aef5ea7",
            "name": "Sohan Shinde",
            "email": "soham@gmail.com",
            "number": "9130354510",
            "rollNumber": 202,
            "departmentID": "6365531fdc02a121ffeed944",
            "classID": "636554e8dc02a121ffeed982",
            "position": "Student",
            "password": "$2a$10$DuXjtayCPgGwkNnpog5IYeEEkY56igtlA/m6vobT44wmlSLcXp1eK",
            "createdAt": "2022-11-06T09:42:53.861Z",
            "updatedAt": "2022-11-06T09:42:53.861Z",
            "__v": 0,
            "counts": [
                {
                    "_id": "6367819d60fa65e95aef5ea7",
                    "count": 2,
                },
                {
                    "_id": "63677d2960fa65e95aef5e95",
                    "count": 3,
                }
            ]
        }
    ]
}

但是我想从我的查询中得到这种类型的数据(计数)。唯一与它的parent _id匹配的数据。注意_id和计数。_id,这样你就可以理解我的请求了。

{
    "data": [
        {
            "_id": "63677d2960fa65e95aef5e95",
            "name": "Lavannya Urkande",
            "email": "lavannya@gmail.com",
            "number": "9130354519",
            "rollNumber": 201,
            "departmentID": "6365531fdc02a121ffeed944",
            "classID": "636554e8dc02a121ffeed982",
            "position": "Student",
            "password": "$2a$10$mqysVgtIGrYbvMGtHE2vbu0z5g05BlwJizcc.CfWMld78VPrnvcrO",
            "createdAt": "2022-11-06T09:23:53.803Z",
            "updatedAt": "2022-11-06T09:23:53.803Z",
            "__v": 0,
            "counts": [
                {
                    "_id": "63677d2960fa65e95aef5e95",
                    "count": 3,
                }
            ]
        },
        {
            "_id": "6367819d60fa65e95aef5ea7",
            "name": "Sohan Shinde",
            "email": "soham@gmail.com",
            "number": "9130354510",
            "rollNumber": 202,
            "departmentID": "6365531fdc02a121ffeed944",
            "classID": "636554e8dc02a121ffeed982",
            "position": "Student",
            "password": "$2a$10$DuXjtayCPgGwkNnpog5IYeEEkY56igtlA/m6vobT44wmlSLcXp1eK",
            "createdAt": "2022-11-06T09:42:53.861Z",
            "updatedAt": "2022-11-06T09:42:53.861Z",
            "__v": 0,
            "counts": [
                {
                    "_id": "6367819d60fa65e95aef5ea7",
                    "count": 2,
                }
            ]
        }
    ]
}
sy5wg1nm

sy5wg1nm1#

您可以在您的$project中使用filter方法

const data = await StudentSchema.aggregate([
  { $match: { classID: mongoose.Types.ObjectId(`${req.params.id}`) } },
  {
    $lookup: {
      from: "attendances",
      pipeline: [
        {
          $match: {
            subjectID: mongoose.Types.ObjectId(`${req.params.Sid}`),
          },
        }, {
          $group: {
            _id: "$studentID",
            count: { $sum: 1 }
          }
        },
      ],
      as: "counts",
    },
  }, {
    $project: {
      classID: 1,
      departmentID: 1,
      email: 1,
      name: 1,
      number: 1,
      position: 1,
      rollNumber: 1,
      counts: {
        $filter: {
          input: "$counts",
          cond: {
            $eq: ["$$this._id", "$_id"],
          },
        },
      },
    },
  },
]);

相关问题