mongodb - 如何使用聚合/填充更改数据层次结构?
问题描述
我有三个系列,为了这个插图的目的,请跟我一起用这个有点问题的书店比喻!
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 集合的属性是没有意义的,但是如果能够抓取特定书籍的类别并将其页面嵌套在其中,那将非常有用。有没有办法使用聚合和人口进行这种操作?
解决方案
推荐阅读
- java - 审核实体的 Dynamics 365 RetrieveAttributeChangeHistory OData 函数
- python - 避免在 django rest 框架序列化程序中验证外键
- python - 如何使用 def 函数创建没有重复的随机列表
- php - 使用 AJAX 更改 PHP 语言 $_SESSION 变量且不重新加载页面
- amazon-web-services - 如何将 .pem 文件导入 AWS Lambda 函数
- c++ - std::map 使用。这里有什么问题?核心转储?我做错了什么?
- flutter - Flutter 方法通道传递 JSON
- css - 如何将图像定位在 div 元素中的背景上?
- python - 将包含 UTF-8 和 Null 的 DataFrame 转换为字符串而不丢失数据
- vb.net - VB.NET Web 应用程序中模块构造函数的执行顺序