In the last article we gave an introduction to the MongoDb document database. We learned how to insert simple independent documents. This article will demonstrate how to persist nested documents into the MongoDb database using C# driver.


Before running any of the code samples make sure that the MongoDb server is running. You can run the server by finding the mongod.exe file and executing it.

Persisting Document Hierarchy:

In the last article we demonstrated how easy it is to store an independent document into the database. The following code shows the details:

The above code will simply insert a new document into the "categories" collection. You can make sure by retrieving the document using the following code:

The above code uses the FindOne method to fetch the document by its Title.

The examples discussed above persisted single documents to the database. In real world applications a document can have a list of other documents.

Persisting hierarchical documents in MongoDb is similar to persisting a single document. All you need to do is to insert a document collection into the parent document and then persist the parent document.

In the code above we created the category document and then added Products to the category document. The "Products" key is used to represent products inside the category document.

In order to retrieve the category with the products you just need to get the category and the products will be populated automatically since they are nested inside the "category" document.

If you run the above code it will print out the "Title" of the category and the "Title" of the Products.

You can even add multiple products as shown in the example below:

In order to insert a list of products you must convert the products into an array as shown in the above code. Later we iterated through the collection and printed the product's "Title".


In this article we learned how to persist a document with nested structure into the MongoDb database. In the next article we will implement a converter which will convert C# objects to Document objects.