Display MongoDB with document and subdocument example and update


Following is the syntax showing document and subdocument −

db.yourCollectionName.insertOne(
   {
      yourFiledName:yourValue,
      yourFieldName : [
         {
            yourFiledName1,
            yourFiledName2,
            .
            .
            .
            N
         }
      ]
   }
);

Let us see an example create a collection with documents −

> db.demo706.insertOne(
...    {
...       PortalName: "GameApplication",
...       ApplicationConfiguration : [
...          {
...             "URL": "jdbc:mysql://localhost/customer_tracker?autoReconnect=true",
...             "USERNAME": "root",
...             "PASSWORD": "root"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6f557551299a9f98c93c6")
}
>
> db.demo706.insertOne(
...    {
...       PortalName: "WebMyBusinessApplication",
...       ApplicationConfiguration : [
...          {
...             "URL": "jdbc:oracle:thin:@localhost:1521:xe",
...             "USERNAME": "App",
...             "PASSWORD": "App"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6f558551299a9f98c93c7")
}

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

> db.demo706.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] }
{ "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "WebMyBusinessApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] }

Following is the query to update −

> db.demo706.update({PortalName: "WebMyBusinessApplication"},{$set:{"PortalName":"OnlineCustomerTracker"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo706.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] }
{ "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "OnlineCustomerTracker", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] }

Updated on: 14-May-2020

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements