使用聚合在MongoDb中分组

时间:2018-11-25 13:19:14

标签: mongodb mongoose mongodb-query aggregation-framework

我是MongoDB的初学者,发现聚合函数很难理解。

我阅读了许多主题并尝试了许多事情,但是无法获得想要的结果。

实际上,我有两种模式:

1)Faculty.js

const FacultySchema = new Schema({

    name: {
        type: String,
        required: true
    }

});

2)Semester.js

const SemesterSchema = new Schema({

    name: {
        type: String,
        required: true
    },

    faculty: {
        type: Schema.Types.ObjectId,
        ref: 'faculties'
    }   

});

学期收据

[
  {
    "_id": ObjectId("5bf82da745209d0d48a91b62"),
    "name": "1st Semester",
    "faculty": ObjectId("5bf7f39a1972dd0b6c74de7d"),
    "__v": 0
  },
  {
    "_id": ObjectId("5bf8c3f945209d0d48a91b63"),
    "name": "2nd Semester",
    "faculty": ObjectId("5bf7f39a1972dd0b6c74de7d"),
    "__v": 0
  },
  {
    "_id": ObjectId("5bf8c3fe45209d0d48a91b64"),
    "name": "3rd Semester",
    "faculty": ObjectId("5bf7f39a1972dd0b6c74de7d"),
    "__v": 0
  },
  {
    "_id": ObjectId("5bf8c40345209d0d48a91b65"),
    "name": "4th Semester",
    "faculty": ObjectId("5bf7f39a1972dd0b6c74de7d"),
    "__v": 0
  }
]

我要分组的是将所有这些学期安排为在同一位置具有相同教员编号的数组。  像这样:

[
{faculty: "BBA", semesters: ['first', 'second', 'third']},
{faculty: "BCA", semesters: ['first', 'second', 'third']}
];

我该如何实现?

1 个答案:

答案 0 :(得分:1)

您可以使用$group聚合来首先找到不同的faculties,然后使用$lookup从“学院”集合中获取names的{​​{1}}

faculties

或者您可以先使用$lookup,然后$group使用不同的Semester.aggregate([ { "$group": { "_id": "$faculty", "semesters": { "$push": "$name" } }}, { "$lookup": { "from": "faculties", "let": { "facultyId": "$_id" }, "pipeline": [ { "$match": { "$expr": { "$eq": ["$_id", "$$facultyId"] }}} ], "as": "faculty" }}, { "$project": { "semesters": 1, "faculty": { "$arrayElemAt": ["$faculty.name", 0] } }} ])

names