부모 참조가 있는 모델 트리 구조
개요
This page describes a data model that describes a tree-like structure in MongoDB documents by storing references to "parent" nodes in children nodes.
패턴
The 부모 참조 pattern stores each tree node in a document; in addition to the tree node, the document stores the ID of the node's parent.
다음과 같은 카테고리 계층 구조를 고려하세요:
The following example models the tree using 부모 참조,
storing the reference to the parent category in the field parent
:
db.categories.insertMany( [ { _id: "MongoDB", parent: "Databases" }, { _id: "dbm", parent: "Databases" }, { _id: "Databases", parent: "Programming" }, { _id: "Languages", parent: "Programming" }, { _id: "Programming", parent: "Books" }, { _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.createIndex( { parent: 1 } ) You can query by the
parent
field to find its immediate children nodes:db.categories.find( { parent: "Databases" } ) To retrieve subtrees, see
$graphLookup
.