MongoDB – Embedded Documents
MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents.
Notes –
- In MongoDB, you can only nest document up to 100 levels.
- The overall document size must not exceed 16 MB.
Creating Embedded Documents –
In MongoDB, you can easily embed a document inside another document. As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document.
Syntax:
{ .... field: {field1: value1, field2: value2} .... }
Let us discuss this concept with the help of the given examples –
Example 1:
Suppose we have a database named ‘GeeksforGeeks’. Now this database has a collection named ‘Courses’ and this collection contains a document. Inside this document, we have a field named ‘name’ which contains another document and this document contain three fields(i.e, first, middle, last) with their values.
Example 2:
Again, we are taking GeeksforGeeks database. Inside this database, we already have a collection named ‘Courses’, now we add another document in this collection, which contains the details of the student who select paid courses. Inside this document, we have a field named ‘courseDetails’. This field contains a document and this document contains some field-value pairs and a sub-document which contains the paymentDetials.
So, overall the Courses collection contains two documents and these documents contain nested documents.
Please Login to comment...