发布于 2015-09-14 14:46:44 | 109 次阅读 | 评论: 0 | 来源: 网络整理

Overview

Data in MongoDB has a flexible schema. Collections do not enforce document structure. Decisions that affect how you model data can affect application performance and database capacity. See 数据建模 for a full high level overview of data modeling in MongoDB.

This document describes a data model that describes a tree-like structure in MongoDB documents by storing references to “parent” nodes in children nodes.

Pattern

The Parent References pattern stores each tree node in a document; in addition to the tree node, the document stores the id of the node’s parent.

Consider the following example that models a tree of categories using Parent References:

db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
db.categories.insert( { _id: "Postgres", parent: "Databases" } )
db.categories.insert( { _id: "Databases", parent: "Programming" } )
db.categories.insert( { _id: "Languages", parent: "Programming" } )
db.categories.insert( { _id: "Programming", parent: "Books" } )
db.categories.insert( { _id: "Books", parent: null } )
  • The query to retrieve the parent of a node is fast and straightforward:

    db.categories.findOne( { _id: "MongoDB" } ).parent
    
  • You can create an index on the field parent to enable fast search by the parent node:

    db.categories.ensureIndex( { parent: 1 } )
    
  • You can query by the parent field to find its immediate children nodes:

    db.categories.find( { parent: "Databases" } )
    

The Parent Links pattern provides a simple solution to tree storage, but requires multiple queries to retrieve subtrees.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务