Trees in MongoDBPosted on 引用地址:%20in%20MongoDB.html 树结构存储最好的方式常常依赖于要执行的操作;下面讨论一下不同的存储方案。在实践中,许多开发人员找到了一些使用起来很方便的模式:单文档存储整根树(Full Tree in single Document),父连接(P
Trees in MongoDB Posted on
引用地址:%20in%20MongoDB.html
树结构存储最好的方式常常依赖于要执行的操作;下面讨论一下不同的存储方案。在实践中,许多开发人员找到了一些使用起来很方便的模式:“单文档存储整根树(Full Tree in single Document)”,“父连接(Parent Links)”和“祖先数组(Array of Ancestors)”。
1 模式 1.1 单文档存储整根树(Full Tree in Signle Document){
comments: [
{by: "mathias", text: "...", replies: []}
{by: "eliot", text: "...", replies: [
{by: "mike", text: "...", replies: []}
]}
]
}
优点:
缺点:
1.2 (父连接)Parent Links用单个集合来存储所有节点,服务器空间,每个节点包含他父节点的ID,是一种简单的解决方案。这种方法最大的问题是获取完整子树时需要查找多次数据库(或使用db.eval函数)。
> t = db.tree1; > t.find() { "_id" : 1 } { "_id" : 2, "parent" : 1 } { "_id" : 3, "parent" : 1 } { "_id" : 4, "parent" : 2 } { "_id" : 5, "parent" : 4 } { "_id" : 6, "parent" : 4 } > // find children of node 4 > t.ensureIndex({parent:1}) > t.find( {parent : 4 } ) { "_id" : 5, "parent" : 4 } { "_id" : 6, "parent" : 4 } 1.3 (子链接)Child Links另一种选择是在每个节点文档中存储所有子节点的ID。这个方法是有限制的,如果不操作完整子树是没有问题。他可能也是用于存储一个节点有多个父节点情况的最有效方法。
> t = db.tree2 > t.find() { "_id" : 1, "children" : [ 2, 3 ] } { "_id" : 2 } { "_id" : 3, "children" : [ 4 ] } { "_id" : 4 } > // find immediate children of node 3 > t.findOne({_id:3}).children [ 4 ] > // find immediate parent of node 3 > t.ensureIndex({children:1}) > t.find({children:3}) { "_id" : 1, "children" : [ 2, 3 ] } 1.4 (祖先数组)Array of Ancestors在这种方法中将一个节点的所有祖先节点存储到一个数组中。这使得类似于“获取X节点的所有子节点”的操作快且容易。
> t = db.mytree; > t.find() { "_id" : "a" } { "_id" : "b", "ancestors" : [ "a" ], "parent" : "a" } { "_id" : "c", "ancestors" : [ "a", "b" ], "parent" : "b" } { "_id" : "d", "ancestors" : [ "a", "b" ], "parent" : "b" } { "_id" : "e", "ancestors" : [ "a" ], "parent" : "a" } { "_id" : "f", "ancestors" : [ "a", "e" ], "parent" : "e" } { "_id" : "g", "ancestors" : [ "a", "b", "d" ], "parent" : "d" } > t.ensureIndex( { ancestors : 1 } ) > // find all descendents of b: > t.find( { ancestors : 'b' }) { "_id" : "c", "ancestors" : [ "a", "b" ], "parent" : "b" } { "_id" : "d", "ancestors" : [ "a", "b" ], "parent" : "b" } { "_id" : "g", "ancestors" : [ "a", "b", "d" ], "parent" : "d" } > // get all ancestors of f: > anc = db.mytree.findOne({_id:'f'}).ancestors [ "a", "e" ] > db.mytree.find( { _id : { $in : anc } } ) { "_id" : "a" } { "_id" : "e", "ancestors" : [ "a" ], "parent" : "a" }ensureIndex和MongoDB的multikey特性可以使上面的查询更高效。
除了祖先数组,我们也存储了节点的直接父节点,使得查找节点的直接父节点更容易。
1.5 物化路径(Materialized Path[Full Path in Each Node))物化路径使得对树的特定查询容易。我们在每个节点中存储文档在树中位置的全路径。通常情况下上面提到的“祖先数组”方法都工作很好;当不得不处理字符串建造、正则表达式,字符逃逸,物化路径更容易。(理论上,物化路径将会更快。)
MongoDB实现物化路径最好的方式是将路径存储成字符串,然后采用正则表达式查询。以“^”开头的正则表达可以被高效执行。把数据看作一个字符串,你需要选择一个分隔符,我们采用“,”。举例:
> t = db.tree test.tree > // get entire tree -- we use sort() to make the order nice > t.find().sort({path:1}) { "_id" : "a", "path" : "a," } { "_id" : "b", "path" : "a,b," } { "_id" : "c", "path" : "a,b,c," } { "_id" : "d", "path" : "a,b,d," } { "_id" : "g", "path" : "a,b,g," } { "_id" : "e", "path" : "a,e," } { "_id" : "f", "path" : "a,e,f," } { "_id" : "g", "path" : "a,b,g," } > t.ensureIndex( {path:1} ) > // find the node 'b' and all its descendents: > t.find( { path : /^a,b,/ } ) { "_id" : "b", "path" : "a,b," } { "_id" : "c", "path" : "a,b,c," } { "_id" : "d", "path" : "a,b,d," } { "_id" : "g", "path" : "a,b,g," } > // find the node 'b' and its descendents, where path to 'b' is not already known: > nodeb = t.findOne( { _id : "b" } ) { "_id" : "b", "path" : "a,b," } > t.find( { path : new RegExp("^" + nodeb.path) } ) { "_id" : "b", "path" : "a,b," } { "_id" : "c", "path" : "a,b,c," } { "_id" : "d", "path" : "a,b,d," } { "_id" : "g", "path" : "a,b,g," }Ruby实例:
嵌套数据集:

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.