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 updating multiple 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 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.Employees.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.upsert  also partially updates an object in MongoDB so that the new object will overlay or merge with the existing one.In brief, upsert is also used to update a document with the contents of another document, but only updates the fields that are absent and completely ignore the fields that are already set.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! Your one-stop-shop for MongoDB is just a click away. Access our live online training and find easy solutions to all your queries here.

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 updating multiple 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 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.Employees.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.
upsert  also partially updates an object in MongoDB so that the new object will overlay or merge with the existing one.

In brief, upsert is also used to update a document with the contents of another document, but only updates the fields that are absent and completely ignore the fields that are already set.

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! 


Your one-stop-shop for MongoDB is just a click away. Access our live online training and find easy solutions to all your queries here.

Nandan

Nandan Kumar

Author

QA Automation Architect having 12+ Years of experience in UI , Backend and Database testing ( Selenium, Cucumber, Gherkins, Protractor, TestNG) having strong Python/Java Coding skills. Strong experience in Devops/QAops , MongoDB and Certified AWS Solution Architect.


Strong Problem solver having worked on multiple domains: Media and TV/Video Streaming, Investment Banking, E-Commerce/Payments and Cloud Security /Networking/SaaS/IaaS/PaaS. 

Join the Discussion

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

Suggested Blogs

7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by techjury, there are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website.The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview.1. Learn how to design In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skillset. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview.  2. Be proficient in basic languages Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledgebase articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 3. Learn multiple platforms Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 4. Learn the basics of editing tools We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on.  5. Create an online portfolioThe best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online.  6. Be prepared to create a mock website Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible.  7. Relax, there are plenty of opportunities We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. Ace your next web development interview These are some core areas that every web developer needs to be proficient at. With the stiff competition today, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.
6654
7 Things to Keep in Mind Before Your Next Web Deve...

Websites are an integral component of any business... Read More

Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript used pretty much everywhere. For the seventh year in a row, we see it ranking as the most popular and widely used programming language, a good 67.8% of developers having used it in 2019. JavaScript is used to build 95.2% (1.52 billion) websites today, including Facebook and YouTube and some of the most popular and useful apps such as Google Maps and eBay. Let’s take a closer look at what JavaScript is, how and why it was created, and how it seems to be taking over front-end development. It all began in the late 90s when Netscape Navigator, a popular browser was launched by Netscape Communication. In the initial days of Netscape, it was just a software which was able to render static HTMLs, but people wanted it to do more. Netscape envisioned that web pages should be more dynamic in nature. If users are not able to engage with HTMLs, browsers will end up becoming boring pieces of software, they figured.That’s when Brendan Eich came into the picture. He was contracted in 1995 by Netscape Communications to develop a language which would have a low learning curve, so that anyone would be able to write functionalities with it. He developed the language in just 10 days and named it Mocha. A working prototype of Mocha was integrated in the Netscape Browser in May 1995, renaming the language to LiveScript and later in December 1995, it was renamed again, this time as JavaScript. The marketing team at Netscape chose to call it "JavaScript" as Java was extremely popular at that time. With the popularity of Netscape Navigator, Microsoft wished to capture the browser market and developed Internet Explorer with a scripting language named JScript. For a long time, there was no common standard formed for JavaScript, resulting in huge cross browser compatibility issues. Finally, in 1997, Netscape invited ECMA (European Computer Manufacturing Association) to take the responsibility of forming a specification for JavaScript.Since then, the ECMA has released updated specifications for JavaScript regularly and browsers try to follow these specifications in their implementation of JavaScript engine.Fact Check: Today, Brendan Eich is the CEO of Brave Software which builds a privacy oriented, chromium-based browser named Brave.Fact Check: Netscape Navigator later became the foundation stone for Mozilla Firefox. They retained the same name for their JavaScript engine "Spider Monkey" which was part of the Netscape navigator.Need of Framework With the ECMAScript specifications in place, developers began to use JavaScript  to make the HTML page much more dynamic using JavaScript. However, there were still a few developers who preferred to write big client-side functionality with JavaScript, owing to low performance of browser and JavaScript engines. Perhaps, the industry had a more a server-side performance focus in that era. Then, as computers became more powerful, browser performance improved and JavaScript engines evolved, developers started moving client-side logic to browser using JavaScript.Once developers started writing more and more JavaScript, the community felt the need to write logic in a more structured and scalable manner, so as to be more understandable, readable, manageable and less error prone. The need for a framework in JavaScript was clearly felt.Many frameworks like Dojo, Backbone, Ember and AngularJS eventually emerged within their own communities, which tried to solve problems in their unique way. Collectively, this has helped the whole JS community to move forward towards a more scalable and maintainable web application. ReactJS In 2011, Codebase for Facebook Ads was getting bigger. Developers began to face maintenance issues with it and it was getting harder to add new features in an efficient way. That's when Facebook engineer, Jordan Walke, built a prototype for an efficient application UI. This marked the birth of ReactJS, initially called FaxJS. Later, when Instagram was acquired by Facebook, the folks at Instagram wanted to adopt this framework. Pete Hunt and Jordan Walke then improved, decoupled the library and made it open source as ReactJS in 2013. Since then ReactJS has gone through many changes. The latest version of ReactJS in 2020 is currently 16.13. ReactJS follows component-based architecture and encourages developers to think in terms of small, composable components. Interestingly, this methodology is aligned with an efficient approach for solving any problem in life: the first step to solve a big problem is to break it down into multiple smaller sub problems. Once you have a solution for each sub-problem, you can then add it up to get the overall solution. This can be applied to all problems, big or small. ReactJS asks developer to adopt a problem-solving approach like this to build any UI. It must be noted that ReactJS does not aim to solve each and every problem of building a web application. Rather, it has a narrow focus and a limited scope to solve the one core problem of web development around how to efficiently updating the UI/views.When ReactJS was open sourced in the JSConf 2013, the ideas and changes that ReactJS was proposing were not very well received. For instance, although two-way binding was very popular, ReactJS went ahead with one way data flow. In another example, writing HTML inside JS was considered a bad practice, but ReactJS still wanted to use JSX. All these ideas initially attracted a lot of criticism from the web developer community. In time, however, developers started using it and found it easy to build components efficiently. So, ReactJS now solved the one problem around updating views. But what about all the problems in web development? An ecosystem began to emerge to address the other problems along with ReactJS. Libraries like Redux and React-Router came to life, making ReactJS a complete web framework, although this meant that there would be a dependency on multiple libraries. The ease of using ReactJS trumped all the negative points of the framework and this is what continues to make it a very popular library in web development. In 2020, ReactJS has 50K plus stars on Github and is downloaded 6 million times per week. The ReactJS ecosystem continues to grow steadily; React Native recently bought ReactJS to build cross mobile platform apps. Libraries like Gatsby and NextJS encourage developers to use ReactJS on server and provide benefits of server-side rendering without much hassle. ReactJS has also stood out in multiple developer surveys such as the State of JavaScript. Main design concepts in ReactJS Main design concepts in ReactJSDeclarative, composable, reusable componentsReactJS motivates developers to write small components and reuse the same component at multiple places. Re-usability of components greatly speeds up the overall development and results in less amount of code. Less code is always better because it is less prone to errors. ReactJS encourages developers to write composable components which can be wrapped around any other React component to provide special functionality, thus discouraging the writing of components that do too many things. ReactJS always encourages developers to break their problem into smaller problems, solve the smaller problems first and then combine them to present the overall solution. Less functionality in components always leads to less error prone components. ReactJS encourages developers to write clean, readable, and maintainable code. This is why it emphasizes writing declarative components, which make a codebase easier to read and understand by fellow developers.Declarative, composable components looks a lot like HTML in JS. Instead of standard HTML tags, we have React components as tags. This similarity to standard web semantics is what makes JS somewhat familiar to developers starting out. Reactive Updates Writing static HTML is no fun and it can be said that JavaScript was born to bring interactivity to web pages. ReactJS helps developer to add functionalities in components with which the user can interact and see the results. ReactJS allows developers to attach a state to component and whenever the state of components changes, the component efficiently re-renders itself to produce an updated view. Now, the state of the component can be changed by clicking a button, entering text into the input box or any other part of the component triggering an event. The React component listens to these events and acts accordingly. Updating the whole component UI seems like a terrible idea, but ReactJS has implemented this terrible idea wonderfully by doing it efficiently. In-memory DOM representation ReactJS is able to efficiently update views by keeping a DOM representation in memory known as virtual DOM. Upcoming updates always compare the new DOM with an older copy of the DOM and based on the difference, it figures out the actual DOM elements which need to be updated on the UI. Reducing the number of DOM manipulations makes ReactJS faster. What this means is that writing smaller React components will take up less memory to store DOM representations (Virtual DOM) and ultimately, this results in better performance. Features of ReactJS Main features of ReactJSJSX and Why is it needed When ReactJS was released, it was mentioned in documentation that it is recommended to use JSX along with ReactJS. Now, what is JSX? and do i really need another library to use the ReactJS library? So, let us see how a simple ReactJS component looks without JSX: 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")  ); There is no way the above code looks like a declarative component. The truth is JavaScript does not understand HTML or XML like tags. That is why we need someone to do that conversion for us. Here enters JSX, also known as a syntax extension for JavaScript. With JSX, the above Greeting React component will look something like this: import React from "react";  function Greeting({ name }) {    return {`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root")); JSX actually makes ReactJS code more readable and understandable. You can assume this as a templating library which converts HTML looking syntax into ReactJS element JS code by calling createElement(). Virtual DOM ReactJS has made the term, 'VDOM' or virtual DOM very popular in the JavaScript community. Web browsers have provided APIs to interact with DOM to make our web page dynamic. One can dynamically add or remove nodes in the web page by using these APIs. But interacting with these APIs was very slow, as changing node triggers re-layout and re-paint event for sub-tree. Although the entire subtree is re-rendered (diffing stops when an element type has been modified and subtree is freshly rendered), even in case of virtual DOM reconciliation, the advantage that React offers is that the developer is freed from figuring out which part of DOM really requires updates - the diffing and reconciliation algorithm takes care of it.  React has thus provided a way to reduce the number to change in DOM using virtual DOM. The VDOM is a JavaScript object which contains information of DOM sub tree. We can also call this an object representation of DOM. React uses this object to compare subsequent modification and figure out the minimum number of modifications needed to make in browser DOM to get the desired result. ReactJS claims that the wonderful performance of their library is because of the algorithm they use to compare the virtual DOM. React Native React native is another popular library which is used to build cross platform mobile applications using JavaScript. Before ReactJS, Cordova and ionic were some frameworks which were very popular to build mobile applications using JavaScript. However, these applications did not perform very well. React native uses popular component-based concepts of ReactJS and provides a way to build an efficient mobile application. React native converts JS code into native platform code to run in mobile devices. This approach has improved the performance of mobile applications by a great deal in comparison to other frameworks like ionic. With React Native, ReactJS has now become a very popular library to build UI on any platform. ReactJS: Here to stay Over the past decade, the JavaScript community has seen tremendous changes in language within the developer community. It has seen a lot of new ideas and terms surface in the form of libraries. Developers are building and sharing their work with rest of the world quite frequently and every other day, implementations are open sourced on Github. These new ideas and the problem solving approach continues to help the JavaScript ecosystem to evolve and become better. Prior to ReactJS, JQuery was very popular and was the default library for any web project involving DOM manipulation. With AngularJS and other MVC libraries, we were encouraged to think about a problem in terms of Modal, View and Controller. People have always sought to figure out an approach that can solve the problem. And structuring a solution in a scalable manner is not a new challenge either. We have already implemented scalable solutions at server-side, and they are performing quite well. ReactJS now brings the same pattern to the front-end, where the final output is a UI. To implement this, we break the problem into smaller sub-problems and write solutions for them. This is the basic mental model to solve all UI problems and ReactJS focuses on the same. New ideas in the JavaScript community help the community move forward and eventually, the best solutions become part of the standard JS (ECMAScript). ES modules, promises and some lodash utilities are examples of this. When a library moves in the same general direction as the web, it is bound to be used by a large community. Developers will use these solutions until new specifications are finalized and browsers adopting new specifications. Interim, people will use the feature in the form of third party library.So, is ReactJS moving in the right direction? I would say yes. ReactJS is evolving right along the evolving standards of JavaScript. The front-end community is leaning more towards concepts of functional programming rather than object-oriented methodology. In a similar direction, ReactJS continues to move towards a functional programming pattern. ReactJS has introduced hooks in version 16.8, which encourages developer to build more and more functional components instead of class-based components. Hook does not even work with class-based component. Understanding well that it sometimes becomes a hectic task to figure out which library one should choose to handle state management, ContextAPI and useReducer hooks have been introduced, which help in managing state in small applications much better. Today, with the help of ContextAPI and useReducer hooks, you can build an application without using any other library like Redux. This, however, does not mean that you should stop using Redux as it has its own benefits.Component based architecture is also aligned with the standard web components support in browsers, which allow developers to write non-standard HTML tags in code. In short, ReactJS has made the community become familiar with some of the upcoming web standards. For this reason, I feel that conceptually, ReactJS is going to stay with the community for long. Many big companies like Facebook, Microsoft and AirBnB are supporting the direction and concepts of ReactJS, thus adding credibility to the library. With many big brains backing the library, the ReactJS community looks poised for growth. With no perfect solution to all the problems in web development in sight, the best option is to move forward with whatever is available at the moment. In the JavaScript community too, there is an effort to figure out an alternate to ReactJS such as VueJS and Svelte. Perhaps, ReactJS will get replaced by some other library in the future. However, the basic idea of creating smaller, reusable components is here to stay.Whatever framework we learn, it is most important to grasp the basic idea behind the library. It is this idea or design pattern that is going to remain for good. It may appear in front of you in a different form and shape, but the idea will remain forever. 
9963
Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript u... Read More

Exploring the Various Decorators in Angular

There are several important concepts in Angular, and Decorators are an important concept to learn when you are working with version 2 and above of Angular. Through this post we will learn about decorators, its types and how it is being used in real time applications.  Decorators are an important concept in TypeScript and since Angular uses Typescript widely, decorators become an important part of Angular as well.  What are Decorators? Decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method or property. They allow a service, directive or filter to be changed before being used. Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work. There are various types of in-built decorators. Let’s look at each type of decorator in detail. Types of Decorators: There are four types of decorators and each type further has its own subset of decorators.  Class Decorators  This is the first type of decorator which tells us about a particular class’s intent and helps answer questions like whether the class is a component or a module. There are various Class decorators in Angular, and among them @Component and @NgModule are widely used. Let’s see the structure of class decorators via a code snippet. Explanation: The below code snippet uses @Component, which is a type of class decorator provided by Angular.Property Decorators Property decorators are used to decorate specific properties inside a class. Using a property decorator, we can easily identify why we use any particular property of a class Like @Input (), @Output, @ReadOnly (), @Override () The above code uses @Override decorator before the property name which will invoke the decorator. This is nothing but a function and will override the string property name from “pat” to “test”. Method Decorator  Method decorators, as the name indicates, are used to decorate the method defined inside our class with functionality. A common example of method decorator is @HostListener In the above screen shot @HostListener decorator is used before onHostClick () method. Parameter Decorators Parameter decorators allow us to decorate parameters in our class constructors.  @Inject () is a common and widely used parameter decorator. Using this decorator, we can inject services in Angular classes. Structure of Decorators  In all the code snippets that we have seen so far on decorators, you must have noticed that each of the decorators follows a similar pattern or structure when used in code. Each decorator starts with @ symbol and is added before the class, method, property or passed as a parameter. All are functions having open and close brackets. This helps us understand that it is the function which is used as an in-built decorator. Just like a function can be customized, decorators can also be customized. Based on the requirement in our project, we can create custom decorators and use them accordingly. Custom Decorator  In this section we are going to learn the steps involved in creating custom decorators. As the term custom itself suggests, it is something which we create based on our project need which is not already fulfilled by the in-built Angular decorator. So, whenever we want to add some more features to our class, property of class, or method of class we use custom decorators. Here we are going to create a custom class decorator. Step 1. In an Angular project solution structure, create a classes folder inside the app folder.  Inside the classes folder create a class named sample Demo . Step 2. Once the class is created, you can go ahead and create a folder inside the app folder called decorator and add a file name as class.decorator.ts  Step 3. As we know decorators are functions, so we will create a function named Logging, as follows: ‘target’ is the class on which this decorator is going to be used and as we are going to use this decorator on class sample Demo, we have added export keyword before this function. Step 4. As we are going to use this decorator in the sample demo, let us add the sample demo class with decorator.  If we add this class in our main component and invoke, we will see the output on console as custom decorator SampleDemo How to pass data to a decorator The example explained above is a simple custom decorator where we are logging some messages on the console along with the class name where it is used. But if we want to send messages through the class where we are adding the decorator, then we have to change the implementation of the Function Logging.  Function Logging will accept some arguments and return the message as passed by the decorator on class. When we use the decorators in Angular, we pass in some form of configuration, specific to the decorator. For example, when we use @Component we pass through an object, and with @HostListener we pass through a string as the first argument (the event name, such as 'click') and optionally an array of strings for further variables (such as $event) to be passed through to the decorated method. Uses of Decorators in Real Time Applications Almost all Angular applications use decorator concepts; as decorators are functions that allow a service, directive or filter to be modified prior to its usage. @override, @deprecate, @autobind, @mixin are decorators which are widely used in real time applications. Angular framework has several of these kinds of examples which help to achieve complex features in applications. We know now what Angular decorators are and how they work on class, property, methods and parameters to provide information about metadata. All decorators work on a similar principle. We can apply some changes to the behaviour of the default functionality or we can add some custom tweaks to the code before the decorator can be applied to a class, property or method.  There are different ways to call decorators as these decorators can control start from the class implementation to the property and method implementation within the class. Decorators are great when code needs to be customized to suit the needs of the clients and when in-built functions do not help us with what we need.  Summary  When it comes to Angular decorators, we have several options to inject our codes and logic on different levels of class; as everything in programming revolves around class and its objects. Angular, being a rich framework gives us wide options to handle things in our own way. TypeScript has introduced this concept of decorators and those wishing to implement decorators into their code will benefit from going through TypeScript documents to understand more about actual implementation of decorators and its advanced concepts.