提问人:Christopher Robin 提问时间:11/17/2023 最后编辑:Christopher Robin 更新时间:11/17/2023 访问量:42
访问 MongoDB 中的嵌套结构
Access to the nested structure in MongoDB
问:
我正在为具有以下层次结构的教育课程设计一个 API 和数据库结构:课程 -> 模块 -> 课程 ->主题 -> 任务(正文)。
[
{
_id: ObjectId('a...')
name: "How to cook borscht",
modules: [
{
id: ObjectId('b...'), // Perhaps not ObjectId, I haven't figured it out yet.
title: "Analyzing the composition",
lessons: [
{
id: ObjectId('c...'),
title: "Selecting the Cabbage"
topics: [
id: ObjectId('d...'),
title: "White Cabbage",
tasks: [
id: ObjectId('e...'),
description: "White cabbage is a common vegetable crop, one of the cultivated variants of the species Brassica oleracea."
]
]
}
]
}
]
}
]
假设对 /api/courses 的第一个请求会将课程结构作为程序描述返回给用户。然后,要开始学习,我需要将所有作业一起返回第一课。topics[0]
modules[$id].lessons[$id].topics[$id].tasks
完成课程后,它旨在记录课程已完成(这可能需要一个单独的表,其中包含用户及其活动的列表)。假设所有课程内容都将存储在一个文档中,并且可能会有不同的翻译(文档大小可能会超过 16MB)。
问题:如何设计文档结构以有效地检索特定课程的任务列表?
答:
0赞
user22919420
11/17/2023
#1
// Course document
{
"_id": ObjectId("a..."),
"name": "How to cook borscht",
"modules": [
{
"_id": ObjectId("b..."),
"title": "Analyzing the composition",
"lessons": [
{
"_id": ObjectId("c..."),
"title": "Selecting the Cabbage",
"topics": [
{
"_id": ObjectId("d..."),
"title": "White Cabbage",
"tasks": [
{
"_id": ObjectId("e..."),
"description": "task_id_1" // Reference to translations collection
}
]
}
]
}
]
}
]
}
// Translations collection
{
"_id": ObjectId("task_id_1"),
"translations": {
"en": {
"description": "White cabbage is a common vegetable crop, one of the cultivated variants of the species Brassica oleracea."
},
"es": {
"description": "La col blanca es un cultivo de hortalizas común, una de las variantes cultivadas de la especie Brassica oleracea."
}
// Add more translations as needed
}
}
翻译可以保存在单独的集合中,并以这种方式在主文档中引用。您可以在搜索特定课程或活动时使用查找来检索翻译。您可以通过在任务的_id字段上创建索引来按 ID 有效地搜索任务。MongoDB 会自动在_id列上构造索引,因此您无需为其执行任何异常操作。MongoDB在按_id查询作业时,将使用该索引进行快速查找。
db.courses.findOne({
"modules.lessons.topics.tasks._id": ObjectId("e...")
},
{
"modules.lessons.topics.tasks.$": 1
})
评论
0赞
Christopher Robin
11/17/2023
谢谢你的榜样!你能告诉我,如果我需要翻译文本并且文档大小超过 16MB,我该怎么办?第二个问题是,在收藏中寻找的最佳方式是什么?tasks[$id]
0赞
11/20/2023
如果您需要文本翻译,并且文档大小超过 16MB,您可能希望探索一种设计,其中翻译存储在单独的集合中并引用主要内容。通过这种方式,您可以使主文档更小、更易于管理。
评论