content_image/728164.jpg
<img src='content_image/728164.jpg'>

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.createIndex( { 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. 

## Model Tree Structures with Child References 

## 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 Data Modeling Concepts (page 145) 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 (page 147) in the parent-nodes to children nodes. 

