首页 > 解决方案 > 如何使用聚合/填充更改数据层次结构?

问题描述

我有三个系列,为了这个插图的目的,请跟我一起用这个有点问题的书店比喻!

3个集合;书籍、页面和类别。书籍有很多页面,每个页面都根据其内容进行分类。

var page = mongoose.Schema({    
    book          : { type: Schema.Types.ObjectId, ref: 'Book' },
    category      : { type: Schema.Types.ObjectId, ref: 'Category' },
    content       : { type: String }
});

var book = mongoose.Schema({    
    pages       : [{ type: Schema.Types.ObjectId, ref: 'Author' }], 
    pageCount   : { type: Number },
    title       : { type: String },
});

var category = mongoose.Schema({
    title           : String,
    color           : String,
    sortOrder       : Number
});

给定一本书的 id,我想查看它的页面并将它们返回到相应类别的数组中,以获得类似的结果......

{
    categories: [
        {
            title: "Diagrammatical",
            color: "Red",
            sortOrder: 1,
            pages: [
                {
                    _id: ObjectId("a3j3n2i"),
                    book: ObjectId("12345"),
                    content: "Page Content Here"
                },
                {
                    _id: ObjectId("30gjkdi2g"),
                    book: ObjectId("67890"),
                    content: "Other Page Content Here"
                }
            ]
        },
        {
            title: "Prose",
            color: "Green",
            sortOrder: 2,
            pages: [
                {
                    _id: ObjectId("abcdefg"),
                    book: ObjectID("12345"),
                    content: "Page Content Here"
                },
                {
                    _id: ObjectId("hijklmn"),
                    book: ObjectId("67890"),
                    content: "Other Page Content Here"
                }
            ]
        }
    ]    
}

在我的用例中,将页面设置为 Category 集合的属性是没有意义的,但是如果能够抓取特定书籍的类别并将其页面嵌套在其中,那将非常有用。有没有办法使用聚合和人口进行这种操作?

标签: mongodbaggregation-framework

解决方案


推荐阅读