如何使用mongodb拼合顶级文档和子文档?

时间:2018-06-19 11:51:20

标签: mongodb mongodb-query

我正在处理mongoDB查询。

让我们假设我正在处理以下学校数据,其中每个级别都有唯一的标识符。为了这个例子,假设我们有每个教室的姓氏列表:

School1
    Division1
        Classroom1
            Student1 last name
            Student2 last name
        Classroom2
            Student3 last name
            Student4 last name
    Divison2
        Classroom1
            -
        Classroom2
            -
School2
    -
        -
        -
    -
    -

我现在想编写一个查询,以这种格式获取所有学生的所有“扁平化”信息:

{
    School1,
    Division1,
    Classroom1,
    Student1 last name,
},
{
    School1,
    Division1,
    Classroom1,
    Student2 last name,
},
{
    School1,
    Division1,
    Classroom2,
    Student3 last name,
},
......

这是我到目前为止所拥有的:

db.students.aggregate(
[
    {
        $project: {
        school: "$school._id",
        division: "$school.division._id", 
        classroom: "$school.division.classroom._id",
        student: "$school.division.classroom.student._id",
        }
    },
        {$unwind:"$school"},
        {$unwind:"$division"},
        {$unwind:"$classroom"},
        {$unwind:"$student"},
]
)

通过此操作,我可以获取所需的信息,但格式不正确:

school: school1,
division: { division1},
classroom: {classroom1, classroom2},
student: {student1, student2, student3, student4}

什么是一个好的方法?

1 个答案:

答案 0 :(得分:0)

$unwind之后进行投影:

db.students.aggregate(
[
    {$match: {}},
    {$unwind:"$school"},
    {$unwind:"$division"},
    {$unwind:"$classroom"},
    {$unwind:"$student"},
    {
        $project: {
            school: "$school._id",
            division: "$division._id", 
            classroom: "$classroom._id",
            student: "$student._id",
        }
    },
]
)