30 Days of node
Day 12 : CRUD operations in mongodb






30 days of node - Nodejs tutorial series
What is MongoDb ?

Classified as a No SQL database , MongoDB is a scalable, open source, high performance , document-oriented database designed by keeping developers agility in mind. It is document-oriented which means that it does not store data in tables and rows as we would in relational databases like MySQL, In this we store data in JSON-like documents with dynamic schema.
Advantages :

  1. Dynamic schema : If we have an flexible schema then it is ideal for JSON-like documents as in MongoDB however it is difficult to implement it in a good manner in Relational databases.
  2. Scalability : MongoDB is highly scalable
  3. Cheap : Can be downloaded free of cost.

Prerequisites

  1. MongoDb : You can download it here .
  2. Node.js : You can download it here .
  3. NPM : It is already installed on your system when you installed node.js
  4. mongodb (npm package) : We can install it using the command given below :
    											
    >npm install mongodb
    											
    										

Establishing connection with db

The first step is to establish a connection between the mongodb database and our node.js application.

								
//Including the required packages
var mongo = require('mongodb');
//Establishing the connection
var new_db = "mongodb://localhost:27017/demo_db"
								
							

Here ,
  • demo_db is the name of the db to be created
  • 27017 is the port number where mongodb is running.
  • localhost signifies that currently the db is running locally.

Now , We will establish the connection using the connect method. Connect() is an inbuilt method used to is an inbuilt method used to Creates a connection to a MongoDB instance and returns the reference to the database. It instantiates a new connection to the MongoDB instance running on the localhost interface and returns a reference to demo_db. Snippet for establishing connection using connect method is given below :
								
//File Name is  : demo-db.js
//establishing the connection
mongo.connect(new_db ,(error , db) => {
	if (error){
		throw error;
	}
	console.log("Database demo_db created successfully");
	//To close the connection
	db.close();
});
								
							

We can run the above code using the following command :
								
> node demo-db.js
Database demo_db created successfully
								
							

Congratulations , we successfully established a connection with mongodb using node.js

Insert/Create Operation in MongoDb

  1. insertOne() : insertOne() is an inbuilt method which is used to insert data in the mongoDb collection. Snippet for the following is given below :
    								
    //Name of the file  : insert-mongo.js
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}
    	
    	var data = { name : "rishabhio" , age : "25" , mobile : "1234567890" }
    	
    	db.collection("details").insertOne(data, (err , collection) => {
    		if(err) throw err;
    		console.log("Record inserted successfully");
    		console.log(collection);
    	});
    });
    								
    							

    We can run the above code using the following command :
    								
    > node insert-mongo.js
    >node insert_mongo_nodejs.js
    Record inserted successfully
    { result: { ok: 1, n: 1 },
      connection: null,
      message: undefined,
      ops:
       [ { name: 'rishabhio',
           age: '25',
           mobile: '1234567890',
           _id: 597073b2c6f60f5b3c23a1a5 } ],
      insertedCount: 1,
      insertedId: 597073b2c6f60f5b3c23a1a5 
    }
    								
    							

Read Operation in MongoDb

  1. findOne() : findOne() is an inbuilt method which is used to Read the first occurance of the data from the mongoDb collection.
    											
    //name of the file : read-one.js
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}
    	//findOne() reads the first occurance of any data from the database.
    	db.collection("details").findOne({}, (err , collection) => {
    		if(err) throw err;
    		console.log("Record Read successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    
    											
    										

    We can run the above code using the following command :
    											
    > node read-one.js
    Record Read successfully
    { name: 'Nodejsera',
      age: '23',
      mobile: '9876543210',
      _id: 59706a56a4f6761e3cc22c98 }
    											
    										

  2. find() : find() is an inbuilt method which is used to Read all data from the mongoDb collection.
    											
    //name of the file : read-all.js
    mongo.connect(new_db , function(error , db){
    	if (error){
    		throw error;
    	}
    	
    	//Read All the data from the "details" collection.
    	db.collection("details").find({}).toArray( (err , collection) => {
    		if(err) throw err;
    		console.log("Record Read successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    											
    										

    We can run the above code using the following command :
    											
    > node read-all.js
    Record Read successfully
    [ { name: 'Nodejsera',
        age: '23',
        mobile: '9876543210',
        _id: 59706a56a4f6761e3cc22c98 },
      { name: 'rishabhio',
        age: '25',
        mobile: '1234567890',
        _id: 59706c3771da112bd8b922dc },
      { name: 'rishabhio',
        age: '25',
        mobile: '1234567890',
        _id: 597073b2c6f60f5b3c23a1a5 } ]
    											
    										

Update data in an document

  1. updateOne() : updateOne() is an inbuilt method of mongodb which is used to search the first occurance of the data and update it.
    											
    //name of the file : update-one.js
    mongo.connect(new_db ,(error , db) => {
    	if (error){
    		throw error;
    	}
    	//Query parameter is used to search the collection.
    	var query = { name : "rishabhio" };
    	//And When the query matches the data in the DB , "data" parameter is used to update the value.
    	var data = { name : "nodejsera.com" , mobile : "1234567890" }
    	//Accessing the collection using nodejs
    	db.collection("details").updateOne(query , data, (err , collection) => {
    		if(err) throw err;
    		console.log("Record updated successfully");
    		console.log(collection);
    	});
    });
    
    											
    										

    We can run the above code using the following command :
    											
    > node update-one.js
    Record updated successfully
    { result: { ok: 1, n: 1, nModified: 1 },
      connection: null,
      message: undefined,
      modifiedCount: 1,
      upsertedId: null,
      upsertedCount: 0,
      matchedCount: 1 }
    											
    										

  2. updateMany() : updateMany() is the inbuilt method of mongodb which is used to search for the given query and update all its occurances.
    											
    //name of the file : update-all.js
    mongo.connect(new_db ,(error , db) => {
    	if (error){
    		throw error;
    	}
    	
    	//query store the search condition
    	var query = { age : {$gt : "22" } };
    	//data stores the updated value
    	var data = { $set : {age : "above 22" } }
    	//CREATING A COLLECTION IN MONGODB USING NODE.JS
    	db.collection("details").updateMany(query , data, (err , collection) => {
    		if(err) throw err;
    		console.log(collection.result.nModified + " Record(s) updated successfully");	//It will console the number of rows updated
    		console.log(collection);
    		db.close();
    	});
    });
    											
    										

    We can run the above code using the following command :
    											
    > node update-all.js
    node updateMany-mongodb-nodejs.js
    3 Record(s) updated successfully
    { 	result: 
    		{ 
    			ok: 1,
    			n: 3,
    			nModified: 3 
    		},
    	connection: null,
    	message: undefined,
    	modifiedCount: 3,
    	upsertedId: null,
    	upsertedCount: 0,
    	matchedCount: 3 
     }
    
    											
    										

Delete a document

  1. deleteOne() : deleteOne() is the inbuilt method of mongodb which is used to delete the first occurance of the data provided in the search query.
    											
    //name of the file : delete-one.js
    mongo.connect(new_db ,(error , db) => {
    	if (error){
    		throw error;
    	}
    	//query stores the search condition	
    	var query = { age : "above 22" };
    	
    	//Accessing a COLLECTION IN MONGODB USING NODE.JS
    	db.collection("details").deleteOne(query , (err , collection) => {
    		if(err) throw err;
    		console.log(collection.result.n + " Record(s) deleted successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    
    											
    										

    We can run the above code using the following command :
    											
    > node delete-one.js
    1 Record(s) deleted successfully
    { 
    	result: 
    		{ 
    			ok: 1,
    			n: 1
    		},
    	connection: null,
    	message: undefined,
    	deletedCount: 1 
    }
    
    											
    										

  2. deleteMany() : deleteMany() is the inbuilt method of mongodb which is used to delete all the occurances of the data provided in the search query.
    											
    //name of the file : delete-all.js
    mongo.connect(new_db ,(error , db) => {
    	if (error){
    		throw error;
    	}
    	
    	//Search query for deletion
    	var query = { age : "above 22" };
    	
    	//Accessing the collection
    	db.collection("details").deleteMany(query , (err , collection) => {
    		if(err) throw err;
    		console.log(collection.result.n + " Record(s) deleted successfully");
    		console.log(collection);
    		db.close();
    	});
    });
    
    											
    										

    We can run the above code using the following command :
    											
    > node delete-all.js
    2 Record(s) deleted successfully
    { 
    	result: 
    		{ 
    			ok: 1,
    			n: 2
    		},
    	connection: null,
    	message: undefined,
    	deletedCount: 2 
    }
    											
    										

Summary

In this chapter of 30 days of node tutorial series, we learned about how we can establish a connection with a MongoDb database using node.js and perfrom the basic create, read, update and delete operations.