Search

How to Update Document in MongoDB

MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. Updating Single document Syntax: db.collection.update(query, update, options) Use the update method  Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. Use the $set operator to update the values  Choose the Field Name that needs to be updated and enter the new values accordingly –  Employee_Name =”Daniel Morales”db.Employees.update( {"Emp_ID" :100}, {$set:{"Employee_Name" :"Daniel Morales"}}); WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })Updating Multiple documents Syntax: db.collection.update(query, update, options) For updatingmultiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time. The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. Use the update method  Specify the condition which you should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. Use the $set operator to update the values  Choose the Field Name(s) that needs to be updatedand enter the new values accordingly – Employee_Name =”Nandan Kumar” Emp_ID = 21db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})MongoDB save() Method  The db.collection.save() method is used to update an existing document or insert a new document Syntax: db.collection.save() db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({“ nInserted" : 1 })The save() method returns a WriteResult object which contains the status of the insert or update operation. During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:db.Employees.find(); {"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . Note -  If the document doesn’t contain an _id field, then the save() method calls the insert() method. db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})The save() method performs an update with upsert: true since the document contains an _id field:  db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })Note -  If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : MongoDB updateOne() method This method updates a single document within a collection matching the filter or condition. Syntax The syntax of updateOne() method is − db.collection.updateOne(<filter>, <update>) Example> db.Employees.updateOne( {First_Name: 'Nandan'}, { $set: { Age: '30',e_mail: 'nandan@gmail.com'}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }MongoDB updateMany() method The updateMany() method updates all the documents within a collection based on the filter or condition . Syntax : The syntax of updateMany() method is − db.collection.updateMany(<filter>, <update>) Example>db.Employees.updateMany(  {Age:{ $gt:"25"}},  { $set:{Age:'12'}}  )  {"acknowledged":true,"matchedCount":2,"modifiedCount":2}Using the find command, you can retrieve the contents of the documents:> db.EmpDetails.find() { "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345" } { "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" } { "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update( {type:"FullTime"}, {$set:{salary:20000}}, {upsert : true} )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the Write Result of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection. Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . This command works as both updateOne and updateMany command. db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    } )Here, it will update only first document which matches the condition.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    }, { multi: true } // Additional Parameter )Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .db.collection.updateOne() --> method to update only one document in a collection.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated      } )This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False.You can also update multiple parameters but they need to be separated by a comma (,). E.g.$set: { "bonusEligiblity": "False" , “emp_status : ”New”},db.collection.updateMany() --> method to update multiple document in a collection matching the specified conditiondb.Employees.updateMany(    { "joinYear": "2020" },   { $set: { "bonusEligiblity": "False" },   } )Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update(      {type:"FullTime"},      {$set:{salary:20000}},      {upsert : true}   )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the WriteResult of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.Conclusion   To summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed. db.collection.update(query, update, options) In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function. Hope this has been useful. The MongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding! 
Rated 4.0/5 based on 13 customer reviews

How to Update Document in MongoDB

8K
How to Update Document in MongoDB

MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. 

In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. 

Updating Single document 

Syntax: db.collection.update(query, update, options) 

  1. Use the update method  
  2. Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. 
  3. Use the $set operator to update the values  
  4. Choose the Field Name that needs to be updated and enter the new values accordingly –  
Employee_Name =”Daniel Morales”
db.Employees.update(
{"Emp_ID" :100},
{$set:{"Employee_Name" :"Daniel Morales"}});
WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })

Updating Multiple documents 

Syntax: db.collection.update(query, update, options) 

For updatingmultiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time. 

The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. 

  1. Use the update method  
  2. Specify the condition which you should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. 
  3. Use the $set operator to update the values  
  4. Choose the Field Name(s) that needs to be updatedand enter the new values accordingly – 
Employee_Name =”Nandan Kumar”
Emp_ID = 21
db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})

MongoDB save() Method  

The db.collection.save() method is used to update an existing document or insert a new document 

Syntax: db.collection.save() 

db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({“ nInserted" : 1 })

The save() method returns a WriteResult object which contains the status of the insert or update operation. 

During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:

db.Employees.find();
{"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }

In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . 

Note  If the document doesn’t contain an _id field, then the save() method calls the insert() method. 

db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})

The save() method performs an update with upsert: true since the document contains an _id field:  

db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })

Note -  

If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. 

Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : 

MongoDB updateOne() method 

This method updates a single document within a collection matching the filter or condition. 

Syntax 

The syntax of updateOne() method is − 

db.collection.updateOne(<filter>, <update>) 

Example

> db.Employees.updateOne(
{First_Name: 'Nandan'},
{ $set: { Age: '30',e_mail: 'nandan@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

MongoDB updateMany() method 

The updateMany() method updates all the documents within a collection based on the filter or condition . 

Syntax : 

The syntax of updateMany() method is − 

db.collection.updateMany(<filter>, <update>) 

Example

>db.Employees.updateMany( 
{Age:{ $gt:"25"}}, 
{ $set:{Age:'12'}} 
) 
{"acknowledged":true,"matchedCount":2,"modifiedCount":2}

Using the find command, you can retrieve the contents of the documents:

> db.EmpDetails.find()
{ "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345" }
{ "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" }
{ "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }

What If the update operation doesn’t match documents in collection? 

If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.

db.Employees.update(
{type:"FullTime"},
{$set:{salary:20000}},
{upsert : true}
)

WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   

You can also see the upsert getting reflected in the Write Result of the above operation. 

upsert operation in MongoDB is used to save documents into collection . 

If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection. 

Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() 

The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . 

This command works as both updateOne and updateMany command. 

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" },
   }
)

Here, it will update only first document which matches the condition.

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" },
   },
{ multi: true } // Additional Parameter
)

Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .

db.collection.updateOne() --> method to update only one document in a collection.

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated  
   }
)

This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False.

You can also update multiple parameters but they need to be separated by a comma (,). E.g.

$set: { "bonusEligiblity": "False" , “emp_status : ”New”},

db.collection.updateMany() --> method to update multiple document in a collection matching the specified condition

db.Employees.updateMany(
   { "joinYear": "2020" },
  {
$set: { "bonusEligiblity": "False" },
  }
)

Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” 

What If the update operation doesn’t match documents in collection? 

If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.

db.Employees.update( 
    {type:"FullTime"}, 
    {$set:{salary:20000}}, 
    {upsert : true} 
 )

WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   

You can also see the upsert getting reflected in the WriteResult of the above operation. 

upsert operation in MongoDB is used to save documents into collection . 

If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.

Conclusion   

  • To summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed. 

db.collection.update(query, update, options) 

  • In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function. 
  • Hope this has been useful. ThMongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding! 
KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

AngularJS: Top Use Cases and Reasons to Opt for This Tool

AngularJS represents a structural framework for dynamic web applications. It is an open-source, JavaScript-based front-end web platform primarily developed by Google and a consortium of individuals and companies to solve many of the challenges faced in the development of single-page applications.   AngularJS offers flexibility in coding like no other framework due to its simple design architecture. In terms of simplicity, it helps beginners to get started and make improvements to their application projects easily. AngularJS also handles heavy web applications that are exceptionally well loaded with features and components. It allows you to use HTML as your template language and allows you to extend the syntax of HTML to clearly and succinctly express the components of your application. The data binding and dependency injections ensure that we do not need to write a big chunk of code which otherwise we would have ended in writing. And all happens inside the browser making it a perfect partner for any application. The next layer data binding frameworks gains popularity due to strong demand. The foremost known ones are: AngularJS KnockoutJS BackboneJS DurandalJS JavaScriptMVC AngularJS overview AngularJS is a platform and framework that uses HTML and TypeScript to build single-page client applications. The below diagram will give you fair idea of difference in traditional page life cycle vs Single page life cycle : The AngularJS application is written using typescript. It introduces core and optional features when you import a collection of TypeScript libraries into your applications. The architecture of an AngularJS application is based on some fundamental principles.The basic building blocks are NgModules which provide the component compilation background. NgModules compile the related code into functional sets; a collection of NgModules define an AngularJS application. An AngularJS application often has at least one root module that enables bootstrapping, and usually has a lot more feature modules.We will not go into details as this is out of scope of this article but to give you better understanding of an AngularJS application ,let's look at below example where we are trying to calculate area of rectangle :  Area:     Width:     Breadth: Area: {{width * breadth}} This appears to be normal HTML, with some new markup. A file like this is called a Template in AngularJS. Once AngularJS launches the code, it uses the compiler to interpret and process this new markup from the template. The DOM that is loaded, transformed, and rendered is then called view. The Directives are the first kind of modern markup. We add special actions to items or attributes in the HTML. You would have noticed the new attribute ng-app which is a directive for initializing AngularJS apps automatically.AngularJS also defines an input element directive which adds additional behavior to the element. The directive ng-model stores / updates the value of the input field within / from a variable. Why AngularJS? AngularJS is backed by Google. This is a huge relief for developers to operate on a stable code base that will offer the application maximum support. it's a stable platform to focus on. Many frameworks are nowadays a pure bundling of existing resources. They are an integrated group of tools but they are not very elegant. AngularJS is the next generation platform where each tool was built to function in an integrated manner with any other tool. Please find below some reasons why AngularJS is considered as best among its competitors: MVC inbuilt support Most frameworks enforce MVC by asking you to break your app into MVC components and then allow you to write code to re-string them. This is a lot of work. As a developer we have to just split the framework into MVC components and leave everything to AngularJS for taking care. Declarative User Interface AngularJS uses HTML to describe the user interface within the program. HTML is a more concise and less complex declarative language than the procedural interpretation of the JavaScript interface HTML is also less brittle to reorganize than a JavaScript-written GUI, so things are less likely to break. And when the view is written in HTML, you can put in a lot more UI developers. Data models are POJO The POJO acronym for plain old java objects are being used as data models in AngularJS and it works without superfluous functions getter and setter. You can include and change properties straightforwardly and circle over objects and exhibits voluntarily. Your code will look a lot of cleaner and progressively instinctive, the way mother nature expected. Behaviors with Directive Directives are the way AngularJS brings added functionality to HTML. Imagine a world in which HTML has so many rich elements ( e.g. < accordion>, < grid>, < lightbox>, etc.) that we never have to manipulate a DOM to simulate them.To get some functionality out of the box, all that our app needs to do is assign attributes to items. Flexibility with filter Before displaying data on UI, filters filter the data and may include anything as simple as formatting decimal places on a list, reversing the order of an array, filtering a parameter-based array, or implementing pagination. Filters are designed to be stand-alone features, similar to instructions, independent from your device, but concerned only with data transformations. Less code All the points you have received up to now mean you 're getting to write less code. No need to write your own MVC pipeline. The view is described using more succinct, HTML. Without getters / setters, data models are easier to write. Data-binding means you don't have to manually insert data into the view. Also the directives are different from the software code, they can be written in parallel with limited integration issues by another team. Filters let you manipulate view level data without changing controllers. Unit testing ready The definition of AngularJS would be incomplete without speaking of its readiness for unit test. Dependency Injection (DI) links the whole of AngularJS together. Agular's unit tests will use dependency injection for unit testing .It mocks the data and injects into server. In reality, AngularJS already has a mock HTTP provider for controllers to insert fake server responses. It beats the more conventional way web apps are checked by creating individual test pages that activate a single feature and then communicate with it to see if it is working. Google assisted, and a great community of growth. Supported by IntelliJ IDEA and Visual Studio .NET IDEs. Limitations AngularJSis not a magic bullet. Some of its drawbacks are the backsides of its positive points, some of which are intrinsic to JavaScript inefficiency that could not be solved even with the strongest derivatives of its limitations are listed below: AngularJS is broad and complicated. With multiple ways to do the same thing, it's hard to tell which way is best for a particular task. Mastering AngularJS at the "Hello World" level takes significant effort. Different developers' coding styles and habits can complicate the integration of different components into a complete solution. When the project expands over time, you will most likely need to throw away current implementations and build new ones using different approaches. AngularJS implementations are poor in scale. More than 2,000 watchers will seriously lag behind the UI. This limits the complexity of your AngularJS forms , especially large data grids and lists. Best use cases of AngularJS If you want to build smart lightweight applications, AngularJS is your best bet. This TypeScript-based framework helps you to build interactive SPAs that are safe, maintainable, and easy to check. Some of the popular use cases for AngularJS are as follows: YouTube PlayStation three app for video streaming Anyone who likes to play video games would not have skipped the PlayStation 3 version of YouTube. Considering the vast popularity of YouTube, a structure will be needed. Because Google owns AngularJS, it has been leveraged to introduce a brand-new version of YouTube on PlayStation 3. The flexible architecture has helped Google reinvent the PS3 experience by replacing the traditional operating method with a fully new one.  They replaced mouse movements with basic keystrokes. With AngularJS usability, the features of native apps like YouTube PS3 can be extensively leveraged.AngularJS has made a greater contribution in playback video and smooth scrolling on the YouTube PS3. It's the latest ultra-modern and seamless experience of AngularJS, experienced by the crowd of gamers. eCommerce applications like T-Mobile T-Mobile discovered that its customers had to wait for content to be loaded while connecting to the app. So, to make it quicker and less complicated, they used AngularJS server-side rendering to reduce the time. They also used AngularJS so that they could use HTML parsing for search engine purposes.  This leading telecommunications leader has had tremendous success in their eCommerce app, which has generated a phenomenal search engine traffic. With AngularJS, the application interface has been revamped and turned into a smooth and powerful app. Real-time Data Application like weather.com Weather.com is one of the most popular real-time weather update websites. The credit for its success is given to AngularJS 's modular functionality of modules and directories that enable you to use the features of the app on mobile and smartphone devices.  The framework enables developers to build customizable widgets based on the device's specific needs. Using real-time data and dynamically presenting it made it available on the Web using AngularJS technology. What projects don’t need AngularJS AngularJS is super heroic, but there are situations where you can't use AngularJS. Websites with Static Content Small websites with lower targets and static content. These types of websites are better built with limited technical stacks and do not need to be used by AngularJS, as the technology will only add extra pieces of code that are not required by the website or a specific project. Example: landing pages, educational websites, event pages, etc. Limited Resources and Startups AngularJS is not a good idea to start with for small teams and limited resources. AngularJS needs the skillful tools necessary to solve fast problems in large-scale projects. Technology should also not be used for small projects; it can be developed with other available frameworks and does not require much technological facilitation. Game Apps and Heavy Analytical Apps AngularJS is not a gaming app. Other frameworks, such as React, can be used to build a highly interactive UI in games. AngularJS tests every document object model before it changes its position. It is not recommended to use AngularJS in any app which require strong complex mathematical analytics mostly which is used in gaming. Popular web apps built with AngularJS Sharing a list of some of the renowned web applications that are driven by a versatile and robust AngularJS framework: The Guardian The Guardian is a leading designer and publisher, winning a variety of competitions in these fields. The Guardian website UI is created as an AngularJS app.Guardian.comPayPal Papal is one of the world's largest Internet payment firms. This is another one of the big websites that use AngularJS.Paypal.comJetBlue JetBlue is one of the most famous airline companies in the United States as the online airline portal. The new edition of the JetBlue website uses AngularJS.jetBlue.comLego Lego is one of the world's leading producers of play materials. Its products are traded global and can be virtually explored at www.LEGO.com.Lego.comNetflixNetflix is an American MNC entertainment company. It focuses on and offers streaming media and video on demand online and DVD by mail.FreelancerFreelancer.comFreelancer – the global leading online workplace where understanding businesses and professional service provider go to work!WeatherWeather.comWeather.com is one of the top weather forecasting online report websites. It is also one of the biggest websites using AngularJS.YouTube for PS3YouTube App on PlayStationOwned by Google, YouTube is mainly used for video hosting and sharing. This is being developed using AngularJS framework. Conclusion We can conclude that the AngularJS web app development framework surely has a wide range of powerful features that gives AngularJS an edge over its competitors like ReactJS. This is one of the primary reasons large-scale businesses are opting for AngularJS as their preferred choice of web development platform. To summarize the key points about AngularJS. It is easy to learn and master. It makes application stable and fast. A bunch of useful features in one framework. There are tons of reasons why you should choose AngularJS for your next web app. The World loves it. We mastered it.
Rated 4.0/5 based on 13 customer reviews
6719
AngularJS: Top Use Cases and Reasons to Opt for Th...

AngularJS represents a structural framework for d... Read More

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root"));Alright. But is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { }, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (    Decrement  {value}  Decrement    );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`};  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React LifecycleReact lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from https://nodejs.org/en/. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (      -   {count}    +      );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
Rated 4.0/5 based on 15 customer reviews
6715
What Is a React Component? Write Your First React ...

Prior to ReactJS, Popular frameworks like Angular... Read More

How to Create MongoDB Database in Node.js

MongoDB is an open-source platform written in C++. It is a document database designed for ease of development and scaling. It is a cross-platform, document-oriented and non-structured database. This article is a quick guide on how to create MongoDB database in Node.js. We will understand MongoDB compatibility and language compatibility and exploreMongo shell. We will see how to import data into the database, how to use MongoDB driver for node.js and the Node.js based CRUD operations. We will conclude with building a simple app using node express app with MongoDB to store and serve content. How MongoDB is different from relational databases Relational databases are SQL enabled and are organised in tables with each entry containing a specific set of columns with a specific data type.  It is seen that sometimes relational databases become very complex for simple schemas, for e.g., where an employee who has more than one phone number, email IDs, addresses, teams, etc. and all the related data is stored in different tables. To retrieve complete information for an employee, multiple tables needs to be joined and queried.  One of the disadvantages with relational databases is that to update or change schema, we would need to modify multiple tables. As the requirement changes, more updates might be needed, further complicating the design. This makes it necessary for a dedicated DB admin. Mongo is a NoSql DB and is object-based containing an entire entity in document record. Unlike relational database, NoSqldb can be queried faster and easy to get complete details of a specific entity or document.  Another feature of Mongo is if there is no document matching to query than no error is returned. In relational database, a table contains the same set of fields whereas in Mongo DB, schema is dynamic and each one need not conform to the same schema.Mongo is developer friendly and JSON representation makes it easy to parse. MongoDB stores documents in collections. Collections are analogous to tables in relational databases. In MongoDB, databases hold collections of documents. In addition to collections, MongoDB supports: Read-only Views (Starting in MongoDB 3.4) On-Demand Materialized Views (Starting in MongoDB 4.2). MongoDB data structure Documents – JSON Objects Store data as BSON (Binary JSON) [For the BSON spec, see bsonspec.org] The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types var mydoc = {_id: ObjectId("3423jksdhfi83p9fj90cd"),  name: { firstName: "Sachin", lastName: "Tendulkar" },  birth: new Date('Apr 24, 1973'),  awards:[ “Bharat Ratna”, “Padma Vibhushan”, “Padma Shri”]  followers :NumberLong(30000000)  } _id holds an ObjectId,  name holds an embedded document that contains firstName and lastName, birth hold values of Date types awards holds an array of strings followers holds a value of NumberLong type. Note: Mongo supports nesting up to 100 levels. Learn more about bson-types at https://docs.MongoDB.com/manual/reference/bson-types/ Setup MongoDB environment FormacOS platform, download the tgz file and extract the file. Easiest way to get the items in your path is to copy them to usr/local/bin directory. Follow the below steps to get it doneNow type ‘mongod’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’s insert a dummy data and observe that it inserted one document. db.users.insert({“name”: “Sachin Tendulkar”})Database is all setup. For Windows platform, download the msi and run the installation to complete the installation. Once the installation is done, you can find where it has been installed. Two things important in bin folder are mongo and MongoD. Copy the path and add to the path in environment variables.  Once this has been done, we should be able to run both the Mongo Server and Mongo Shell from command prompt.  Invoke the command prompt and do ‘md \data’ and then create data DB by ‘md \data\db’. This is the file that mongo is going to look for to use to store information about database.  Now type ‘mongoD’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’sinsert a dummy data and observe that it inserted one document. db.users.insert({“name”: “Sachin Tendulkar”}) Database is all setup. The recommended way to get started using the Node.js driver is by using NPM (Node Package Manager) to install the dependency in your project. After you’ve created your project with npminit, you can install the MongoDB driver and its dependencies with the command: npm install MongoDB --save This will download the MongoDB driver and add a dependency entry in your package.json file. We will learn more of this as we go forward. Compatibility MongoDB compatibility Note: The driver does not support older versions of MongoDBNode.js DriverMongoDB 4.2MongoDB 4.0MongoDB 3.6MongoDB 3.4MongoDB 3.2MongoDB 3.0MongoDB 2.6>= 3.X✓✓✓✓✓✓✓>= 3.2.1✓✓✓✓✓✓>= 3.1✓✓✓✓✓✓>= 3.0✓✓✓✓✓>=2.2.12✓✓✓✓Language compatibilityNode.jsDriverNode.js v0.8.XNode.js v0.10.XNode.js v0.12.XNode.js v4.X.XNode.js v6.X.XNode.js v8.X.XNode.js v10.x.xNode.js v12.x.x>=3.X.X✓✓✓✓✓2.2.X – 2.0.X✓✓✓✓✓✓>=1.4.18✓✓✓1.4.x✓✓Few salient points When designing the schema for your database, a quick understanding of Embedded vs References is helpful. You can refer Coderwall for more information on this.  Three of the other features that mongo provides: Indexing, Sharding and replicationcan make Mongo the right choice for your application. Indexing- supports ad hoc queries 64 indices per collection Single Field Compound (multiple Fields) Unique Sharding  - Scalability Partitions data onto different machines Scale application into smaller systems Autosharding supported by Mongo Challenging to set upReplicationReliability (Primary and n number of secondary server) Maximizes uptime Replica sets Automatic failoverExplore Mongo Shell Note:All the examples and snaps are taken in macOS. Invoke terminal and type ‘mongod’ which will display the listening port 27017Sinncewe are running locally, we need not secure and optimize it Invoke another terminal (command + T) and type ‘mongo’You should see that we are now connected to MongoDB://127.0.0.1:27017 By default, we are connected to test database  Type ‘db’ to check it in terminal and observe ‘test’ Let us use a different database say ‘MyNewMongoDB’ Type ‘use MyNewMongoDB’ Output: Switched to dbMyNewMongoDB To view all available dbs, type ‘show dbs’.Note: We will not see the new db ‘MyNewMongoDB’. Instead the db is created when the first document is created. Mongo stores data in databases which are separated into collections of documents. To Create a new collection, we need to insert a document and the collection will be created as a side effect. Type ‘db.cricketers.insert({“name”:”Sachin”}) Now check ‘show dbs’ to view our new db Type ‘show collections’ to check that our collection is created.As you can see, mongo doesn’t require any schema or setup work to start working with data. The commands we used are very similar to what we have in SQL but mongo shell uses a JavaScript interpreter. So, we can interact with database using JavaScript expressions making it easy to perform various tasks. Print(‘test’) will print test var arr = [“one”, “two”, “three”] type arrwhich will print the results. Let us take this option to explore further i.e. we will insert 1000 records to db using a for loop.for(i=0;i insert. Read --> find or findOne. Update --> update. Delete --> delete. Node.js based CRUD operations Let ussetup up a simple application using Node.js and MongoDB. We would understand how to setup the driver and perform simple CRUD operations. Follow the below steps to setup project mkdirlearnMongoDB cd learnMongoDB npminit [you would be prompted for inputs related to package.json] npm install MongoDB–save [--save is to update the package.json] Assuming that the mongo db server is still running. If not, start as mentioned earlier. Open the directory learnMongoDB in your favourite IDE. (I am using Visual Studio code). Add a file app.js with the below snippet of code. // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  constassert = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject';  // Create a new MongoClient  constclient = newMongoClient(url);  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  client.close();  }); Observe that we are not providing the db name in the URL. Instead we are getting the db instance on successfully connecting to the server. This way, we can get connected to different databases in the same client instances. Note: We are using assert module to check if connection is successful or not by validating the error object. Will be used for other CRUD operations as well. Run ‘node app.js’ and should observe the log mentioning connected successfully to server. Insertion: Now we have the db object, let’s get hold of the collection and insert some objects into it. Create a function ‘insertDocuments’ to perform insertion into the collection.Call this insertDocuments in the callback of successful connection. // insertDocuments take the db instance  constinsertDocuments = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Insert some documents  collection.insertMany([        {a :1}, {a :2}, {a :3}      ], function(err, result) {  assert.equal(err, null); // assertion to check if any error is there.  assert.equal(3, result.result.n);  assert.equal(3, result.ops.length);  console.log("Inserted 3 documents into the collection");  callback(result); // return the inserted documents      });  }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  console.log(result);  client.close();    })  }); In the callback of the insertDocuments, we get the result object which is as shown below: { result: { ok: 1, n: 3 }, ops: [ { a: 1, _id: 5eeefd2a16f61641f58a9418 },  { a: 2, _id: 5eeefd2a16f61641f58a9419 },  { a: 3, _id: 5eeefd2a16f61641f58a941a } ],  insertedCount: 3,  insertedIds:  { '0': 5eeefd2a16f61641f58a9418,  '1': 5eeefd2a16f61641f58a9419,  '2': 5eeefd2a16f61641f58a941a } } As you can see, result object gives an overview of the action. Ops is the objects added to the collection. And other fields are self-explanatory. Note: You might have noticed that a new field ‘_id’ has been added which is generated by MongoDB for unique identification. If we are not happy with the unique id, we can as well supply like we did during importing of the data. Find: Let’s check if documents added can be retrieved using find. Collection object has a method called ‘find’ which take a parameter i.e. search query to identify the objects. If it is empty then all documents are returned.Invoke the findDouments in the callback of insertion for validating the records inserted. We can use a query filter to get specific item as well. // findDocuments from the db instance  constfindDocuments = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Finds all documents. If required, parameterize the query filter to get specific items.  collection.find({}).toArray(function(err, docs) {  assert.equal(err, null);  console.log("Found the following records");  console.log(docs)  callback(docs);      });    }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  client.close();      })        })  }); For example, if we want to find a specific set of documents based on pre-defined query filter like ‘{‘a’:3}’ : // Find specific document with a query filter  constfindDocuments = function(db, callback) {  // Get the documents collection  const collection = db.collection('documents');  // Find some documents  collection.find({'a': 3}).toArray(function(err, docs) {  assert.equal(err, null);  console.log("Found the following record(s)");      console.log(docs);  callback(docs);    });  } Updation: Now go andupdate a specific document. There are various methods available for updation like update, updateMany, updateOne etc. Use updateOne method to update the first one which matches the query. Signature: updateOne(filter, update, options, callback) Let’s send the filter as {a : 2 } i.e. document whose field a is equal to 2, update as $set: {b:1} to avoid replacement of entire object i.e. adding a new field b to document with value set as 1. Ignore options which is an optional and have a callback to capture post actions. constupdateDocument = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Update document where a is 2, set b equal to 1  collection.updateOne({ a :2 }        , { $set: { b :1 } }, function(err, result) {  assert.equal(err, null);  assert.equal(1, result.result.n);  console.log("Updated the document with the field a equal to 2");  callback(result);      });      }    // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  updateDocument(db, function() {  client.close();          })      })       })  }); Deletion: Let’s use deleteOne method to find and delete the first item with field a and value 3. constremoveDocument = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Delete document where a is 3  collection.deleteOne({ a :3 }, function(err, result) {  assert.equal(err, null);  assert.equal(1, result.result.n);  console.log("Removed the document with the field a equal to 3");  callback(result);      });        }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  updateDocument(db, function() {  removeDocument(db, function(){  client.close();              })          })      })    })  }); Note: All the methods on the collection returns promise object if callback is not passed. So to avoid callback hell as we see above, we can rely on promise and program the code better. Node express app with MongoDB to store and serve content Now that we have fair idea of how to work with MongoDB using mongoshell and node.js driver. Let us build a simple app using node express app with MongoDB to store and serve content. Note: Since this topic is more about MongoDB rather than express, we will keep the express app a basic version. Let us go and comment out all the code in the app.js file from the previous example. We should be left with this: // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  const { equal } = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject'; Invoke a terminal and navigate to the directory where the app.js file is located. Let us install express with the below command. npm install express –save Import the express and body-parser as shown below: constexpress = require('express');  constbodyParser = require('body-parser');  create an app instance and use bodyParser.json().  constapp = express();  app.use(bodyParser.json());  Let the express app be listening on port 3000 with a default route.  app.get('/', (req, res) =>res.send('Express app with MongoDB!'));  app.listen(3000, () =>console.log("App listening at http://localhost:3000")); Consolidated code: constexpress = require('express');  constbodyParser = require('body-parser');  // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  const { equal } = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject';  constapp = express();  app.use(bodyParser.json());  app.get('/', (req, res) =>res.send('Express app with MongoDB!'));  app.listen(3000, () =>console.log("App listening at http://localhost:3000")); In the terminal, run ‘node app.js’ and should see the console log that app is listening in port 3000. To check the default route is working correctly. Invoke the postman and perform get operation.Now let us create a new route to retrieve the document based on field a and parameterized value. app.get('/api/documents/:name', (req,res) => {  }) :name is the parameter being passed. So let’s retrieve it from request parameters. And since we know it is numeric and not string. Let’s parse it to integer. constname = parseInt(req.params.name); Now lets connect to the MongoClient as earlier. This time we will not be using callback approach rather rely on the promise being returned. constclient = awaitMongoClient.connect(url, {useNewUrlParser:true});Since returned object is a promise and in order for the promise to be resolved or rejected. We need to use await keyword before proceeding further. Note: Promise object has two properties i.e. state and result. Promise state property initially has ‘pending’ and post execution will be either ‘fulfilled’(resolve) or ‘rejected’(reject). Similarly, result will be ‘undefined’ initially and then changes to ‘value’[resolve(value)] or ‘error’[reject(error)]. Let us get the db ‘myproject’ and find the first document based on the query filter from collection using findOne method. constdb = client.db(dbName);  constdocument = awaitdb.collection('documents').findOne({"a":name}); Once we get the document, lets return the status as 200 with the obtained document and close the client connection. res.status(200).json(document);  client.close(); As we are using await keyword, we need to add async keyword to the callback. And also lets add a try-catch block to return an error status in case of connection failure as internal server error. app.get('/api/documents/:name',async (req,res) => {  try {     constname = parseInt(req.params.name);  constclient = awaitMongoClient.connect(url, {useNewUrlParser:true});  constdb = client.db(dbName);  constdocument = awaitdb.collection('documents').findOne({"a":name});  res.status(200).json(document);  client.close();            } catch(error) {  res.status(500).json({message:"Error connecting to db", error});      }  }) Now we are good to go and restart our express app. Press ctrl + c and run node app.js to see app is listening at http://localhost:3000. Make sure that MongoDB Server is up and running in the background. Switch to postman and perform a GET operation http://localhost:3000/api/documents/1. This should return the first record in the collection as shown below. {"_id":"5eeefd2a16f61641f58a9419","a":2,"b":1} Same GET request can be performed for other documents by changing the name as 2Similar to get operations, we can configure the routes to perform other CRUD operations on MongoDB to store and serve the content.  Conclusion In this guide, we have gone overMongoDB compatibility and language compatibility and explored the Mongo shell. We have seen how to import data into the database, how to use MongoDB driver and the Node.js based CRUD operations. We have also looked at how to build a simple app using node express app with MongoDB to store and serve content.Armed with this knowledge, you are ready to take a deeper dive into MongoDB and NodeJS. Here’s wishing you the best!  
Rated 4.0/5 based on 13 customer reviews
6523
How to Create MongoDB Database in Node.js

MongoDB is an open-source platform written in C++.... Read More