• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

NodeJS and MongoDB

NodeJS and Mongo

MongoDB is a one of the most popular NoSQL database, which can be used with NodeJS as a database to create database-driven applications. To download a free MongoDB database visit the official website of MongoDB.

Installing MongoDB Module

To download and install the MongoDB module, open the terminal and execute the following command:-

										    
											npm install mongodb
											
										

Now, NodeJS can use this module to manipulate MongoDB databases. To include this module, use the require() method.

										    
											var mongodb = require('mongodb');
											
										

Creating a Database

To create a database in MongoDB, first create a MongoClient object and specify a connection URL with the correct ip address and the name of the database. MongoDB will create the database if it does not exist, and make a connection to it.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												console.log("Database created!");
												db.close();
											});
											
										

Creating a Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. To create a collection in MongoDB, use the createCollection() method.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.createCollection("users", function(err, res) {
												    if (err) throw err;
													console.log("Collection created!");
													db.close();
												});
											});
											
										

Insert Into Collection

To insert a document into a collection, we use the insertOne() method for single document and insertMany() for multiple document. If you don't specify an _id field, then MongoDB will add one for you and assign a unique id for each document.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var userObj = { name: "Uttam", address: "Bangalore" };
												db.collection("users").insertOne(userObj, function(err, res) {
												    if (err) throw err;
													console.log("1 document inserted!");
													db.close();
												});
											});
											
										
										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var usersObj = [
												    { name: "Uttam", address: "Bangalore" },
													{ name: "Divya", address: "Kaluahi" },
													{ name: "Ragini", address: "Bharuch" },
													{ name: "Komal", address: "Bangalore" }
												];
												db.collection("users").insertMany(usersObj, function(err, res) {
												    if (err) throw err;
													console.log("Number of documents inserted: " + res.insertedCount);
													db.close();
												});
											});
											
										

Find Data in a Collection

In MongoDB we have the findOne() and find() methods to find data in a collection. The findOne() method returns the first occurrence in the selection, while find() method returns all occurrences in the selection.

The first parameter of the findOne() method is a query object. In below example we use an empty query object, which selects all documents in a collection and returns only the first document.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.collection("users").findOne({}, function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

The first parameter of the find() method is a query object. In below example we use an empty query object, which selects and returns all the documents in the collection.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.collection("users").find({}).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

Filter the Result

While finding the documents in a collection, you can filter the result by using a query object. The first argument of the find() method is a query object, and is used to limit the search.

Below example will filter the records to retrieve the specific user whose address is "Bangalore".

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: "Bangalore" };
												db.collection("users").find(query).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

You can also find the documents in a collection, and filter it using regular expressions. To find only the documents where the "address" field starts with the letter "B", use the regular expression /^B/.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: /^B/ };
												db.collection("users").find(query).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

Sorting the Result

In MongoDB, the sort() method is used for sorting the results in ascending or descending order. The sort() method takes one parameter, which is an object defining the sorting order.

Below example will sort the result alphabetically by name in ascending order.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var sortingQuery = { name: 1 };
												db.collection("users").find().sort(sortingQuery).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

Below example will sort the result alphabetically by name in descending order.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var sortingQuery = { name: -1 };
												db.collection("users").find().sort(sortingQuery).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});
											
										

Deleting a Document

For deleting a document in MongoDB, we use the deleteOne() method to delete one document and deleteMany() to delete multiple documents. If the query in deleteOne() method finds more than one document, then only the first document is deleted.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: 'Bangalore' };
												db.collection("users").deleteOne(query, function(err, res) {
												    if (err) throw err;
													console.log("1 document deleted");
													db.close();
												});
											});
											
										
										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: /^O/ };
												db.collection("users").deleteMany(query, function(err, res) {
												    if (err) throw err;
													console.log(res.result.n + " document(s) deleted");
													db.close();
												});
											});
											
										

Drop Collection

MongoDB collection can be deleted by using the drop() or dropCollection() method. These two method takes a callback function containing the error object and the result parameter which returns true if the collection was dropped successfully, otherwise it returns false.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.collection("users").drop(function(err, result) {
												    if (err) throw err;
													if (result) console.log("Collection deleted");
													db.close();
												});
											});
											
										
										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.dropCollection("users", function(err, result) {
												    if (err) throw err;
													if (result) console.log("Collection deleted");
													db.close();
												});
											});
											
										

Updating a Document

Document in MongoDB can be updated by using the updateOne() and updateMany() method. In updateOne() method, if the query finds more than one document, then only the first document will be updated.

In the below example we will be updating the address from "Bangalore" to "Mumbai".

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: "Bangalore" };
												var newValues = { $set: { name: "Uttam", address: "Mumbai" } };
												db.collection("users").updateOne(query, newValues, function(err, res) {
												    if (err) throw err;
													console.log("1 document updated");
													db.close();
												});
											});
											
										

If we are using the $set operator, then only the specified fields will be updated. In the below example we will be updating all the documents where the name starts with the letter "U".

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												var query = { address: /^U/ };
												var newValues = { $set: { name: "Rahul" } };
												db.collection("users").updateMany(query, newValues, function(err, res) {
												    if (err) throw err;
													console.log(res.result.n + " document(s) updated");
													db.close();
												});
											});
											
										

Limit the Result

To limit the result in MongoDB, we use the limit() method. This method takes one parameter, a number defining how many documents to return.

Below example will limit the result to only return 2 documents.

										    
											var MongoClient = require('mongodb').MongoClient;
											
											var url = "mongodb://localhost:27017/newdb";
											
											MongoClient.connect(url, function(err, db) {
											    if (err) throw err;
												db.collection("users").find().limit(2).toArray(function(err, result) {
												    if (err) throw err;
													console.log(result);
													db.close();
												});
											});