I want to record all chapters sections paragraphs of a book according to their tree-like parent-child relationship That is a book has many chapters each chapter has many sections each section has many
Yes, MongoDB is a suitable choice for storing and querying hierarchical data like the one you described. MongoDB's document-based model allows for flexible and nested structures, which can represent the parent-child relationship between chapters, sections, and paragraphs.
You can organize your data as follows:
- Create a collection for the book, where each document represents a chapter.
- Each chapter document can have an array field containing section documents.
- Each section document can have an array field containing paragraph documents.
Here's an example structure in JSON:
{
"_id": "chapter_id",
"name": "Chapter 1",
"sections": [
{
"_id": "section_id",
"name": "Section 1",
"paragraphs": [
{
"_id": "paragraph_id",
"content": "Paragraph 1"
},
{
"_id": "paragraph_id",
"content": "Paragraph 2"
}
]
},
{
"_id": "section_id",
"name": "Section 2",
"paragraphs": [
{
"_id": "paragraph_id",
"content": "Paragraph 3"
}
]
}
]
}
Using MongoDB's query language, you can perform various queries to find chapters, sections, and paragraphs based on different criteria, such as names or contents. For example:
- To find a chapter by name:
db.book.findOne({ "name": "Chapter 1" }) - To find a section by contents:
db.book.findOne({ "sections.paragraphs.content": "Paragraph 3" }, { "sections.$": 1 })
Remember to index your data appropriately to optimize the performance of your queries
原文地址: http://www.cveoy.top/t/topic/h1WJ 著作权归作者所有。请勿转载和采集!