Creating hierarchical JSON in MongoDB?



Use the following syntax to create hierarchical JSON in MongoDB −

db.demo716.insertOne(    {       yourFieldName1,       yourFieldName2,       .       .       N,       "fieldName": {          yourFieldName1,          yourFieldName2,          .          .          N,          "fieldname":          [             {                yourFieldName1,                yourFieldName2,                .                .                N             }          ]       }    } );

Let us create a collection with documents −

> db.demo716.insertOne( ...    { ...       "id": 101, ...       "UserEmailId": "John@gmail.com", ...       "UserPassword": "123456", ...       "UserInformation": { ...          "UserName": "Chris", ...          "UserAge": 26, ...          "UserCountryName": "US", ...          "OtherInformation": ...          [ ...             { ...                "TeacherName":"Robert", ...                "SubjectName":"MongoDB", ...                "CollegeName":"MIT" ...             } ...          ] ...       } ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea9b1ff85324c2c98cc4c2f") }

Display all documents from a collection with the help of find() method −

> db.demo716.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5ea9b1ff85324c2c98cc4c2f"),    "id" : 101,    "UserEmailId" : "John@gmail.com",    "UserPassword" : "123456",    "UserInformation" : {       "UserName" : "Chris",       "UserAge" : 26,       "UserCountryName" : "US",       "OtherInformation" : [          {             "TeacherName" : "Robert",             "SubjectName" : "MongoDB",             "CollegeName" : "MIT"          }       ]    } }
Updated on: 2020-05-14T10:16:43+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements