Creating hierarchical JSON in MongoDB?

MongoDBDatabaseBig Data Analytics

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"
         }
      ]
   }
}
raja
Published on 14-May-2020 13:45:11
Advertisements