Introduction about Node.js and MongoDB
Last Updated :
28 Mar, 2019
NoSQL databases are databases that store and retrieve the data that is present in a non-tabular format. Depending on the format of the data stored, NoSQL databases are split into 4 major types:
- Key-Value
- Graph database
- Document-oriented
- Column family
These databases are built to address the shortcomings of traditional RDBMS and provide high performance, availability and increased scaling (horizontally), while also handling data which constantly changes it's schema over time. One of the most popular NoSQL databases which are available today is the MongoDB.
MongoDB is a scalable, high-performance, open-source, document-oriented NoSQL database, which was developed by 10gen in the year 2007. It is written in C++ and it supports a variety of APIs in many programming languages.
Key features of MongoDB:
- Full index support for high performance
- Horizontally scalable and fault tolerant (distributed data storage/sharding)
- Rich document based queries for easy readability
- Replication and failover for high availability
- Map/Reduce for aggregation
- Supports Master-Slave replication
- No joins nor transactions
- No rigid schema, which makes it dynamic
- Data represented in JSON / BSON
When to use MongoDB?
MongoDB can be used in places that require simple queries, easy and fast integration of data and have data whose structure changes constantly with time.
Examples:
- E-commerce websites
- Mobile applications
- Blogs and content management portals
- Storing geospatial data
At the same time, since it doesn't support transactions, it can't be used in highly transactional systems.
SQL vs MongoDB
The components used in MySQL and MongoDB have different terminologies, but similar functions.
SQL | MongoDB |
Database | Database |
Table | Collection |
Row | Document |
Column | Field |
Index | Index |
Installing MongoDB (on windows):
Go to the following link (
https://www.mongodb.com/download-center/community) and download the MongoDB Community Server.
From here, download the MSI file, and install MongoDB in your computer.
After the installation is complete, open the MongoDB Compass Community application, and select the
connect option.
A local instance of MongoDB will now be running on the local host, with the port number 27017.
NodeJS and MongoDB:
Node.js, the open source JavaScript server environment, has the ability to connect to both SQL and NoSQL databases such as MySQL and MongoDB (respectively). In order to use these databases, the required modules need to be downloaded and installed by using the Node Package Manager (npm).
For using the MongoDB, the
Mongoose module needs to be installed.
Installing Mongoose:
Open the command prompt or terminal and type in the following command to install the Mongoose module
npm install mongoose
Connecting to MongoDB using Node.js
The following Node.js script is used to connect to the local instance of MongoDB.
javascript
var client = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/admin';
client.connect(url,{ useNewUrlParser: true }, function(err,db)
{
console.log("Connected");
db.close();
});
Explanation:
- To connect to a database/create a database, a MongoClient object needs to be created.
- The URL of the MongoDB, followed by the database name should be specified
- Using the connect function of the MongoClient object, a connection is established between the server and the MongoDB.
Note: The admin database is being used here.
Running the Node.js file:
Open the command prompt and navigate to the folder which has the js file, and type in the following command.
node filename.js
Note: If the database mentioned in the URL is not present in the MongoDB when a new document is added, the database is created.
Querying data from MongoDB:
The following code snippet is used to query data from the MongoDB databases.
javascript
var client = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
client.connect(url,{ useNewUrlParser: true }, function(err,db)
{
var dbo=db.db("admin")
var cursor = dbo.collection('geeks4geeks').find();
cursor.each(function (err,doc)
{
if(doc!=null)
console.log(doc);
});
db.close();
});
Explanation:
- Using the URL, a connection with the MongoDB server is established.
- Using the DB function, a connection to the admin database is created.
- All the documents present in the geeks4geeks collection is retrieved and displayed in the console.
Note: The admin database is being used here, which contains the collection
geeks4geeks with a few documents in it.
Running the Node.js file:
Open the command prompt and navigate to the folder which has the js file, and type in the following command.
node filename.js
These are the documents present in the admin database's geeks4geeks collection.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read