Search

Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. In this article, we will learn about how we can use a MongoDB database with NodeJS.  But before do that, let’s delve a little into NodeJS. Getting started with NodeJS  So what is Node JS, and why do we use it? NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. Installing NodeJs Plugin for MongoDB:Follow these steps to install Node JS  Install NPM (Node Package Manager).  The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. Double-check that you have npm installed in your system by simply running this command in your terminal: $ npm -v[Text Wrapping Break]6.13.6  Install the Node from NodeJs Website >> NodeJS.   See the type of Operation system and download the version as per your platform compatibility.  Follow the installation guide as suggested by the installer.  Check the node version by running this command in your terminal  $ node -v[Text Wrapping Break]v8.11.4  If you have installed Node before NPM, you will probably need to update your NPM.   npm install npm@latest -g  Installing MongoDB Node.js Driver  The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   npm install mongodb   To see the list of current drivers installed in the system, run the following command:  npm list mongodb  If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. Using Node.JS to connect to MongoDB database   To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.Cluster? What is a cluster?A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here.    Connecting MongoDBNow that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! We will begin with Importing the Mongo Client as shown below: const {MongoClient} = require('mongodb');  To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. const uri = "mongodb+srv://<put-your-username>:<put-your-password>@<write-your-cluster-url>/test?retryWrites=true&w=majority";   Note: You need to update your password and username for the user. Now that we are ready with our URI, create an instance of MongoClient as below: const client = new MongoClient(URI);  Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  await client.connect();  We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  await listAllDatabases(client);  You can put any name to the above function. The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  And, close the connection as below:  finally { await client.close(); }  No, let’s put everything together and call our main function() as:  async function main(){ const uri = "mongodb+srv://<your-username>:<your-password>@<your-cluster-url>/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close(); }  Break]main().catch(console.error);  //To see if there are aby errorsLet’s use our function “listAllDatabases” to list all the databases in our cluster.  async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  (Ensure that the server is running and up!) node list.js  The output should come as below:  Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  Now that we are running with the database, let’s see the different data types they are supported on.  Mongo DB data typesHave you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: String − It is used to store the data. It should be UTF-8 valid. Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. Boolean − To store a boolean (true/ false) value we use this type of data type. Double − Used for storing floating-point values. Arrays − This type of data-type is used for storing list or arrays. Timestamp - This type of data-type is used to check if an element has been modified or added. Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) Null − This type of data-type is used by MongoDB to store a Null value. Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. Object ID − Mongo uses this type of datatype to store the document’s ID. Binary data − Typically used to store binary data. Mongo DB and CollectionsA database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  const collection = db.createCollection(name, options), or  const collection = db.collection(‘books’);     where, name is the connection name which can be anything, The option is a configuration document used for specifying the collection and is optional. We can list the following options while creating a collection: capped, autoIndexId, max, and size. createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. Note: In MongoDB, a collection is never created until it gets some content!  db.collection('check', {strict:true}, function(err, collection) {});    So, this code will never create a collection until and unless you specify and insert it in the document.  ConclusionToday we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  Happy Learning! :)

Introduction to Mongo DB

10K
Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. 

MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  

If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.

If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. 

In this article, we will learn about how we can use a MongoDB database with NodeJS.  

But before do that, let’s delve a little into NodeJS. 

Getting started with NodeJS  

So what is Node JS, and why do we use it? 

NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   

The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. 

Installing NodeJs Plugin for MongoDB:

Follow these steps to install Node JS  

  • Install NPM (Node Package Manager).  

The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. 

Double-check that you have npm installed in your system by simply running this command in your terminal: 

$ npm -v[Text Wrapping Break]6.13.6  
  • Install the Node from NodeJs Website >> NodeJS  
  • See the type of Operation system and download the version as per your platform compatibility.  
  • Follow the installation guide as suggested by the installer.  
  • Check the node version by running this command in your terminal  
$ node -v[Text Wrapping Break]v8.11.4  
  • If you have installed Node before NPM, you will probably need to update your NPM.  
npm install npm@latest -g  

Installing MongoDB Node.js Driver  

The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   

npm install mongodb   

To see the list of current drivers installed in the system, run the following command:  

npm list mongodb  

If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  

Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. 

Using Node.JS to connect to MongoDB database   

To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.

Introduction to Mongo DB

Cluster? What is a cluster?

A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here   

Connecting MongoDB

Now that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! 

We will begin with Importing the Mongo Client as shown below: 

const {MongoClient} = require('mongodb');  

To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. 

Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. 

const uri = "mongodb+srv://<put-your-username>:<put-your-password>@<write-your-cluster-url>/test?retryWrites=true&w=majority";   

Note: You need to update your password and username for the user. 

Now that we are ready with our URI, create an instance of MongoClient as below: 

const client = new MongoClient(URI);  

Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  

await client.connect();  

We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. 

And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  

await listAllDatabases(client);  

You can put any name to the above function. 

The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. 

try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  

And, close the connection as below:  

finally { await client.close(); }  

No, let’s put everything together and call our main function() as:  

async function main(){ const uri = "mongodb+srv://<your-username>:<your-password>@<your-cluster-url>/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close();  Break]main().catch(console.error);  //To see if there are aby errors

Let’s use our function “listAllDatabases” to list all the databases in our cluster.  

async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  

If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  

Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  

(Ensure that the server is running and up!) 

node list.js  

The output should come as below:  

Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  

Now that we are running with the database, let’s see the different data types they are supported on.  

Mongo DB data types

Have you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: 

  • String − It is used to store the data. It should be UTF-8 valid. 
  • Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. 
  • Boolean − To store a boolean (true/ false) value we use this type of data type. 
  • Double − Used for storing floating-point values. 
  • Arrays − This type of data-type is used for storing list or arrays. 
  • Timestamp - This type of data-type is used to check if an element has been modified or added. 
  • Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. 
  • Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) 
  • Null − This type of data-type is used by MongoDB to store a Null value. 
  • Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. 
  • Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. 
  • Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. 
  • Object ID − Mongo uses this type of datatype to store the document’s ID. 
  • Binary data − Typically used to store binary data. 

Mongo DB and Collections

A database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  

const collection = db.createCollection(name, options), or 
const collection = db.collection(‘books’);    

where, 

  • name is the connection name which can be anything, 
  • The option is a configuration document used for specifying the collection and is optional. 
  • We can list the following options while creating a collection: capped, autoIndexId, max, and size. 
  • createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. 

Note: In MongoDB, a collection is never created until it gets some content!  

db.collection('check', {strict:true}, function(err, collection) {});  

 So, this code will never create a collection until and unless you specify and insert it in the document.  

Conclusion

Today we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  

And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  

Happy Learning! :)

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

How To Use Mongodb Text Search?

MongoDB, one of the top NoSQL databases, is well renowned for its rapid speed, versatile structure, scalability, and excellent indexing capabilities. Before we get into the minutiae, let's look at the bigger picture. When it comes to locating content on the internet, full-text search is a must-have function. When we see the material utilizing the phrases or keywords, the best illustration is a Google search. In this post, we will learn about MongoDB's full-text search capabilities based on text indexes.MongoDB debuted with an experimental feature allowing Full-Text Search via Text Indexes in version 2.4. This feature is now an essential element of the product (and is no longer an experimental feature). In this post, we'll go through the fundamentals of MongoDB's full-text search capabilities.Searching Text - An essential featureConsider a normal Google search to better understand the concepts of full-text search. When we use Google to find content, we enter a string of text, strings, phrases, or keywords, and a number of results are returned. Full-text search in MongoDB enables you to run complicated queries comparable to those you'd run using a search engine. You can look for phrases and stemmed variations on a word, and you can also remove specific "negated" terms from your search results.You can create a text index on any field in the document whose value is a string or an array of strings using MongoDB full-text search. When we construct a text index on a field, MongoDB tokenizes and stems the text content of the indexed field and creates the indexes accordingly.Here are some other circumstances in which we might see a full-text search:Consider searching Wiki for your favorite topic. When you input a search term on Wiki, the search engine returns results for all articles that include the keywords/phrases you entered (even if those keywords were used deep inside the article). The relevancy of these search results is determined by their matched score. Consider a social networking site where a user may conduct a search to find all the posts that contain the term cats in them; or, to be more specific, all the posts that have comments that contain the word cats.Setting up for searchLet us now look at some practical examples to help us understand things better. I'd like you to follow along with me by running the examples in mongo shell. We'll start by creating some example data that we'll use throughout the tutorial, and then we'll go through key ideas.To begin, connect to your MongoDB server: Once you have MongoDB installed on your system, you can use mongo shell to connect with a MongoDB server.Run the mongo command from your command prompt to launch the MongoDB shell. The mongo command, by default, launches a shell linked to a locally installed MongoDB instance running on port 27017.Run the mongo command without any further parameters:>mongoThis will produce a welcome message with information about the server to which the shell is connected, as well as the version of MongoDB that is installed.Congrats, you are in mongo shell.Now run the following commands:>use messageLet's use the following statement to insert some documents.db.message.insert({"subject":"Ishan is having a dog", "content":"Dogs are most loyal pet", "likes": 60, "year":2015, "language":"english"}) db.message.insert({"subject":"Dogs eat cats", "content":"Cats are not evil", "likes": 30, "year":2015, "language":"english"}) db.message.insert({"subject":"Cats eat rats", "content":"Rats like cheese", "likes": 55, "year":2014, "language":"english"})Creating an IndexTo execute a text search, we must first establish a text index on the fields. This can be done on a single or numerous fields. The statement below will generate a text index on a single field.>db.message.createIndex({"subject":"text"})Let's use the following statement to insert some documents.db.message.insert({"subject":"Ishan is having a dog", "content":"Dogs are most loyal pet", "likes": 60, "year":2015, "language":"english"}) db.message.insert({"subject":"Dogs eat cats", "content":"Cats are not evil", "likes": 30, "year":2015, "language":"english"}) db.message.insert({"subject":"Cats eat rats", "content":"Rats like cheese", "likes": 55, "year":2014, "language":"english"})Creating an IndexTo execute a text search, we must first establish a text index on the fields. This can be done on a single or numerous fields. The statement below will generate a text index on a single field.>db.message.createIndex({"subject":"text"})We will generate a text index based on the description and subtitle attributes. In MongoDB, we can only construct one text index per collection. So, using the following line, we will establish a compound text index.db.messages.createIndex({"subject":"text","content":"text"})Using the $text operatorThe $text operator can also be used to search a text index. This operator is used to perform text search operations on a text-indexed collection. This operator tokenizes each search string with whitespace and treats most punctuation as delimiters with the exception of – and \." It performs a logical OR operation on the tokens after tokenizing the search phrase. Use the $meta query operator to sort the generated documents.Syntax:  $text:  { $search: , $language: , $caseSensitive: , $diacriticSensitive: }$search FieldWe'll now try to find documents with the keywords 'dog' in the topic and content boxes. We can use the following sentence to accomplish this.> db.message.find({$text: {$search: "dog"}})Example:> db.message.find({$text: {$search: "dog"}},{ subject: 1, content:1}) This will give the output as:   { "_id" : ObjectId("6176ce6de02fd70a168ad9c6"), "subject" : "Ishan is having a dog", "content" : "Dogs are most loyal pet" } { "_id" : ObjectId("6176ce77e02fd70a168ad9c7"), "subject" : "Dogs eat cats", "content" : "Cats are not evil" }Sorting documents based on search relevanceTextScoreEach page that has the search phrase in the indexed fields receives a score from the $text operator. The score shows a document's relevancy to a specific text search query. The score can be specified as part of the sort() method definition as well as the projection expression. The $meta: "textScore" expression offers information about the $text operation's processing. For more information on retrieving the score for projection or sort, see the $meta projection operator.We're doing a text search, thus we'd like to receive some statistics on how relevant the resulting documents are. To do this, we will use the $meta: "textScore" expression, which offers information about the $text operator's processing. Using the sort command, we will also sort the documents by textScore. A greater textScore indicates a better match.db.messages.find({$text: {$search: "dogs"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})This query returns the following documents:{ "_id" : ObjectId("6176b68b750fd1447889f942"), "subject" : "Joe owns a dog", "content" : "Dogs are man's best friend", "likes" : 60, "year" : 2015, "language" : "english", "score" : 1.2916666666666665 } { "_id" : ObjectId("6176b69f750fd1447889f943"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1 }As you can see, the first document gets a score of 1.2916666666666665 (since the keyword dog appears twice in its subject), whereas the second has a score of 1. The query also ordered the returned documents by their score in descending order.Compound Indexing:We will allow compound text indexing on the subject and content fields in our example. Proceed to run the following command in mongo shell:db.messages.createIndex({"subject":"text","content":"text"})This command will not work. Attempting to create a second text index will result in an error message stating that a full-text search index already exists. Why is this the case? The explanation is that text indexes are limited to one text index per collection. As a result, if you want to build another text index, you must delete the old one and establish a new one.db.messages.dropIndex("subject_text")   db.messages.createIndex({"subject":"text","content":"text"})After running the index creation queries listed above, try searching for all pages with the keyword cat.db.messages.find({$text: {$search: "cat"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})The above query will give the following output:{ "_id" : ObjectId("6176b69f750fd1447889f943"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1.3333333333333335 } { "_id" : ObjectId("6176b6cb750fd1447889f944"), "subject" : "Cats eat rats", "content" : "Rats do not cook food", "likes" : 55, "year" : 2014, "language" : "english", "score" : 0.6666666666666666 }Indexing the entire documentIn the last example, we created a composite index on the subject and content fields. However, there may be times when you want any text content in your papers to be searchable.Consider storing emails in MongoDB documents, for example. In the case of emails, all fields must be searchable, including Sender, Recipient, Subject, and Body. In such cases, you can use the $** wildcard specifier to index all of your document's string fields.The query would be as follows (make sure you delete the existing index before establishing a new one):db.messages.createIndex({"$**":"text"})This query would create text indexes on any string fields in our documents.Implementing text search in an aggregation pipeline:Text search is supported in the aggregate pipeline via the $text query operator in the $match stage. But the following regulations apply to text search in the aggregation pipeline:The pipeline's initial stage must be the $match stage with a $text. In the stage, a $text operator can only appear once. The $text operator expression is not permitted in $or or $not expressions. By default, the text search does not return matching documents in the order of matching scores. Use the $meta aggregation expression in the $sort stage to sort by descending score.The $text operator assigns a text score to each document that contains the search word in the index field. The score shows the importance of a document in relation to a given text search query.Examples: The following examples are based on a message collection with a text index on the field subject:>use people > db.people.insert({"name":"Ishan","pet":"dog"}) > db.people.insert({"name":"Abhresh","pet":"cat"}) > db.people.insert({"name":"Madan","pet":"cat"}) > db.people.insert({"name":"Sneha","pet":"dog"}) >db.people.find().pretty()Count the number of the document in which the pet value is dog:db.people.aggregate([{$match:{$text:{$search:"dog"}}},{$group:{_id:null,total:{$sum:1}}}])Count the number of the document in which the pet value is Cat:db.people.aggregate([{$match:{$text:{$search:"dog"}}},{$group:{_id:null,total:{$sum:1}}}])SummaryIf you handle string content in MongoDB, you should use full-text search to make your searches more effective and accurate. In this article, we demonstrated how to conduct a basic full-text search on a sample dataset. Full-text search has always been one of MongoDB's most requested capabilities. This article began with an introduction to full-text search before moving on to the fundamentals of generating text indexes. Following that, we looked into compound indexing, wildcard indexing. We also looked at some key concepts including analyzing text indexes, and text search in the aggregation pipeline. In the forthcoming MongoDB versions, we can expect some significant enhancements to this capability.
4786
How To Use Mongodb Text Search?

MongoDB, one of the top NoSQL databases, is well r... Read More

Installing and Managing Node.JS Using Node Version Manager (Nvm)

Node.js is the backbone of any modern project. It is not just another Backend technology, but also comes in-built with a package manager called npm. The npm package manager is required in all projects which need external node packages like ReactJS or Angular or Vue.Node.js is the second most popular backend technology after Java and is preferred by both start-ups and enterprises to build MERN(MongoDB, ExpressJS, ReactJS, NodeJS), MEAN(MongoDB, ExpressJS, Angular, NodeJS) or MEVN(MongoDB, ExpressJS, VueJS, NodeJS) stack projects. Companies like Netflix, NASA, Trello, PayPal, Uber, Yahoo use them for their large-scale projects. NodeJS is a completely open-source project, as the code is freely available on GitHub. It has a continually active development community. As it is been used in all top tech companies, so it is backed by funding and support from most of them.NodeJS has two ongoing releases, LTS and current, and, therefore two different versions. We will learn about them next.Understanding Node.js releasesIf we go to the NodeJS official site at https://nodejs.org/, we will see that there are two releases going on and they are LTS (Long Term Support) and Current. The LTS version currently is 14.18.1 and Current is 17.0.1.LTS is the stable version that goes through a lot of testing, and has a 30-month development cycle. Anything new that is added to this version will only be the bug fixes during this window. There will be no new features added to Node in this version. As per the NodeJS official site also, this version is recommended for most users. This is the version which is preferred by Enterprise users as they do not want to run into any issues in their large production projects.The other version is the Current version, which is a step ahead of the LTS version. In this version new features are added to the Node language. Sometimes these new features break a lot of things, but mostly they are newer features than those that are available in the LTS version. The current version is preferred by hobbyist programmers or small start-ups which want to work with innovative technologies.Node Version Manager (NVM)Node.js is an open-source project and there are times when we need one version over the other. Suppose we have a stable Production project, which is using the old LTS version. At the same time, we are working on a side-project, which needs the latest NodeJS Current version. In this case we must keep on deleting one Node version, working on the project, and returning to the other version for the other project.This is a very common problem and the best solution is to use nvm (Node.js Version Manager). It lets us switch between different versions of Node without much efforts. We will now understand through examples, how easy it is to switch, install and remove node versions on a system.Installing NVM on LinuxThe installation of nvm on Linux is mainly done through the command line. We are going to illustrate how to install nvm on Ubuntu, but you may note that a similar process can be followed for different flavours of Linux.I am using Ubuntu through WSL (Windows Subsystem for Linux), but the process is the same in an Ubuntu system also.Open the Ubuntu terminal and install wget through the package manager for Ubuntu known as ap-get. Through apt-get, we can easily install any package on an Ubuntu system.We are using the sudo apt-get install wget command. We have to use sudo because to install wget or any other packages, we need admin privileges. It might also ask for a password the first time and we have to give the admin or root password to proceed.Once wget is installed give the below command to install nvm on the Linux system.wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashAfter the command is complete, we will get further commands to properly install nvm on our Linux system.We will run the given three commands separately from the terminal.Next, we will install a node.js version through nvm. Later on, we will see all the commands in more detail. We are using the command nvm install 14.8.1 to install a node version.Once it is installed, we can see the versions of node.js installed on our Ubuntu system by giving the nvm ls command.Installing NVM on macOSThe installation of nvm on mac is mainly done through command line and there are many different ways to do this. But we will follow the brew way, in which we install nvm through the macOS brew command.We need to install Homebrew first to proceed. It is an open-source manager for macOS, which makes it easier to install any software through the command line in macOS. The command to be given on a terminal is shown below. Also make sure that you are using the default bash shell, as this command will give an error in fish or csh shell./bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" It will also ask us for the root password.Once you give the root password the installation will start.There are two ways to install nvm, one is through wget and other is through curl. We need to install these through brew.We can install wget in our mac through the command brew install wget command.Once wget is installed give the below command to install nvm on the mac system.wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashWe can also install curl through brew by giving the command brew install curl in the terminal.The command to install nvm through curl is below.curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashBoth of these installs through wget or curl, will tell us to run the below command on a Mac to install nvm in our shell.So, we need to give these two commands from the terminal to install nvm properly on our mac system.The nvm commands to install and use it are the same on Ubuntu, mac and windows and we will see them in detail later. But we will install a version of node.js on mac to check if it is working properly. We are installing version 14.8.1 through the command nvm install 14.8.1 on our terminal.Now, if we do nvm ls on our terminal, we can see this version along with the other versions installed on our macos system.Installing NVM on WindowsThe installation process for Windows is totally different from MacOS. We will learn to do the same on Windows now, which requires the package nvm-windows. So, first go to https://github.com/coreybutler/nvm-windows/releases and click on nvm-setup.zip file.Once the zip file is downloaded, then extract it. It will be extracted as a single nvm-setup.exe file. Click on the same and the screen for Licence Agreement will appear, as below. But we will also be asked to trust this app in the Windows login screen.Click on “I accept the agreement” and then the Next button.It will give us a destination to install NVM, which we can keep as it is and click on the Next button.Next, it will ask us for the folder to create the Symlink, which we can keep and again click on the Next button.Finally, it will ask us to Install nvm and we can click the Install button now.This will install NVM on your machine. But if you have already installed a version of Node.JS prior to installing NVM, it will ask us for permission to control it. Click on Yes in the pop-up.After NVM is installed successfully, we will get the below screen. We now must click on the Finish button.To verify that the nvm was installed properly, run the command nvm –version from the Windows Terminal and we will get a long list of outputs showing that it was installed.Using NVMThere are various commands which we can use with nvm and change and install any version of node.js with ease. The commands are the same on Windows, MacOS or Linux. The first thing which we must do is to check the versions of node.js installed on the machine. We can do this by using the nvm ls command.As seen in the output, it gives us all the node versions installed on my machine.The most useful command is the nvm install command. Now, this can be used in two ways. We can use it as below –nvm install latest – To install the latest version of node.jsnvm install - To install any version of node.jsWe are using both commands to install the latest and a previous version of node.jsNow, running the nvs ls command will show all of the versions, available on the machine.To use a different version, we just have to use the nvm use command and give the version number. To use the version 17.0.1 in our case, we will give the command nvm use 17.0.1 in terminal. You might get an error like below if you are running this command as a non-admin user.To solve this issue, run the command prompt as an Administrator.Now, again use the nvm ls command and we will see that the 17.0.1 version is in use.We can also uninstall any version of node.js with the nvm uninstall command.SummaryThis article first introduced you to the different Node.JS versions and emphasized the importance of NVM. Next, you learnt how to install it on Ubuntu, then on MacOS and finally on Windows. Lastly, you have learnt about the different commands to install, use and check Node.JS versions. Good luck on your learning journey!
5448
Installing and Managing Node.JS Using Node Version...

Node.js is the backbone of any modern project. It ... Read More

What Are React Keys?

We Love Lists:In React, lists are in the form of arrays in JavaScript which can store multiple values of the same data type. The general need to render lists of items in applications, whether they are web or mobile apps, is because the lists help in displaying the data in the ordered format. This is also mostly used to display the menus on the websites. In other words, lists focus on the UI part of the website, and are mainly used in displaying the menus on a website. Some examples of lists in a website are the navbar menu, sidebar menu etc.In Normal JavaScriptIn the normal JavaScript, the map () function is used to transverse the lists. In the code given below, the map () function is used to take the array of numbers and then multiply the elements of an array with 3. Here we declare a new array variable tripled, assign the new array values that are returned by the map () function and then log it.Codeconst number = [2, 4, 5, 3];  const tripled = number.map((num) => num * 3);  console.log(tripled) Output : [6, 12, 15, 9]Lists in ReactWhile creating a list in React, the map() function is used to traverse the list elements and for updating the content in the lists. We use curly braces {} while working with lists in React.The output obtained through the map() function is assigned to the listItem. We specify the order nature of the list in the output and return a element for each item in the list. Finally, we render the React-DOM and obtain the result using the format at the end. Here’s what the code looks like:Index.jsimport React from 'react';      import ReactDOM from 'react-dom';      import reportWebVitals from './reportWebVitals';  // declaring the constants  const myList = [1, 2, 3, 4, 5];      const listItems = myList.map((myList)=>{      return {myList};      });      // rendering using the ReactDOM, render() function  ReactDOM.render(      {listItems} ,      document.getElementById('root')     );  reportWebVitals();OutputThe line ReactDom.render() method is used to render a React element into the DOM in the supplied container and returns a reference to the component. In this, we are importing any App.js file or any Index.html file for rendering the pages. In the above example we are declaring variables and using the function in the same file itself using the root element.Instead, we are using the “root” to point out the elements present in the index.ex.js file itself. The “root” element is the supplied container in DOM, and ListItem is the component. The root helps to auto render into the documents where it consists of Listelements to be printed out onto the console.How not to render ListIn the above example, we have initialized the list and rendered it using the map() function. We cannot render the list without using the “key” component. If we do so, we may get the output, but we may have some errors in the console. Consider the above example, which is coded without using the key component. In this case we have got the output, but the console has resulted in some warnings. So, it is suggested not to list the components in a program without the key component to uniquely identify the elements in the given list of elements.OutputWhat is the 'key' attribute?In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed. In simple words, the keys help in providing the identity to the elements in the Lists. Keys help to uniquely identify the elements in the Lists.Syntax for Initialization of a KeyIn general, the keys are declared using a flower brace “{}”, and in the braces the corresponding functionality is added to get the output of the program. Keys should be given to the elements that are present inside the array, to provide a stable entity to the elements. To pick the right key from the list, the element should be uniquely identified among the elements in the list.Syntax: -   key = { }How should a key be chosen?It is recommended to choose a STRING as a key, that identifies the items uniquely in a given list. If the given list contains the variable values as strings, and those strings are said to be unique, then the corresponding values can be taken as a KEY. Else if the given list doesn’t contain Strings for variable values, the corresponding variable is type-casted explicitly to strings and then used in the program.By considering the problem encountered in the previous example, we try to remove the warnings using the Key attribute in the above program. After using the key attribute in the above example, we found there are no errors in the console, when we inspected the web page source. In this way the Key attribute is helpful to us in overcoming the errors in the creation of lists in React. The console is illustrated as below:Example of using keyLists.jsimport React from 'react'; // creating a function function Lists(){     const numbers = [1,2,3,4,5]     const listItems = numbers.map((number) =>  {number})     return {listItems} } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // Defining the class named “App” class App extends React.Component {   render() {     return (               Usage of Keys resulted no Errors!                   )   } } export default App;OutputGenerally, the Key is used to identify the elements in a list uniquely. For the unique identification, we can use some alternatives like “id” or “index” forms as Keys from our data.Accessing Key element using ID formLists.jsimport React from 'react'; // Creating the function using function keyword in react function Lists(){     const stringLists = [ 'upgrad', 'knowledge', 'Hut', 'Blog', 'Writing'];         const updatedLists = stringLists.map((strList)=>             {strList} )           return {updatedLists}   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // the class Name is defined here “App” class App extends React.Component {   render() {     return (               Usage of ID Form                   )   } } export default App;OutputWhen we don’t have stable IDs for rendering of items, we use the item Index as the Key to access the elements in the list.Accessing Key Element using Index FormLists.jsLists.jsimport React from 'react'; // defining the function function Lists(){     const stringLists = [ 'bombay', 'delhi', 'calcutta' ];         const updatedLists = stringLists.map((strList, index)=>             {strList} )           return {updatedLists}   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react';  // class Name is defined here class App extends React.Component {   render() {     return (               Usage of INDEX Form                   )   } } export default App;OutputIt is not recommended to use the Indexes for the KEYS, if there is change in the order of items. That action sometimes may result in negative performance and could cause some issues with the Component State.Usage of Keys with ComponentKeys are generally used to identify the unique element in the given list of elements. But, the usage of keys while mapping to the elements describes a particular order. Assigning of keys creates an order and structure that leads to the correct implementation. For example, let us imagine we have created ListItem as a separate component and that ListItem is used for extraction of elements in the list of elements. In this case we should assign the Key component to the in the given array of elements but not to the component present in the ListItem itself.  Example of Incorrect Key usage with ComponentIndex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // Wrong Usage             {item}           );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key should be used here         );   return (                 Incorrect Key Usage Example                 {listItems}           );   }   const myLists = ['csk', 'rcb', 'mi', 'srh', 'kkr', 'dd'];   ReactDOM.render(     ,     document.getElementById('root')   ) reportWebVitals();index.html         REACT TEST       OutputExample of Correct Key usage with Componentindex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // key is not written here       {item}     );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key is written here           );     return (                 Correct Key Usage Example               {listItems}           );   }    const myLists = ['HYD', 'MYS', 'AP', 'GOA'];    ReactDOM.render(     ,     document.getElementById('root')   ) reportWebVitals();index.html           REACT TEST         OutputWhile working with usage of Key with Component, we mostly work on two files namely the JavaScript file (“index.js”) and the HTML file (“index.html”). At this time, we don’t have any work to do with the App.js file, so we comment out the code lines in the file and work only on the index JavaScript and HTML files.The usage of keys in both the examples demonstrated above results in a similar output. But if there is any incorrect usage of keys, we come across errors in the corresponding HTML page on inspection. If the key is used correctly, there will not be any errors if we inspect the page.Keys Uniqueness among its SiblingsWe had learnt that the key should be unique among all the elements in the given list of elements i.e., it should be unique among the siblings in the given list. It is not compulsory that the keys initialized in the program should be Globally unique. We will try to produce two different arrays using the same set of keys as demonstrated below:Index.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals';  function TourBlog(props) {     const place = (               {props.data.map((show) =>                       {show.title}                   )}           );     const famousfor = props.data.map((show) =>               {show.title}: {show.content}               );     return (               {place}                 {famousfor}           );   }   const data = [     {id: 1, title: 'Goa', content: 'Famous For Beaches.....!!'},     {id: 2, title: 'Mumbai', content: 'Famous For Street Food.........!!'},     {id: 3, title: 'Manali', content: 'Famous for Valleys & Beautiful Scenaries....!!'}   ];   ReactDOM.render(     ,     document.getElementById('root')   );   reportWebVitals();index.html           REACT TEST         OutputSummary To sum up what we have learnt in this article:A Key is a unique element among its siblings in the given list of elements.A Key is declared in array format. It takes the String format as a default state to bring the output from the list.If the given elements in the lists are not in the form of strings, they are type-casted into the string form and then accessed using the Key component in React.We can access the key elements using the Id and Index forms.We can use keys along with the Components. In this, we assign the Key component with the respective only, but not to the component unless the particular item type is not specified in the given program.Finally, we have seen the usage of Key component with two types of arrays in the given program itself to generate the result at the end.
5082
What Are React Keys?

We Love Lists:In React, lists are in the form of a... Read More