Home » MongoDB

How to drop a collection in MongoDB?

In this article, we are going to learn about the command or process to drop a MongoDB collection of a database.
Submitted by Manu Jemini, on February 02, 2018

As we know all MongoDB is a non-sql database. This make it easy for web developers to manage data-base because of the simplicity in which the data is been store in MongoDB .

A record is a mongo document that is composed of field and value pairs. The documents are like JSON objects. Just like JSON in mongo we can put more documents inside a document.

So, we basically used it to store data without the usage of SQL queries.

To drop a collection in MongoDB through an Express server we need to full fill certain requirements:

  1. You must have MongoDB install.
  2. npm install MongoDB.
  3. You must import mogodb in the express server, var MongoDB = require(’MongoDB ’)
  4. You should always specify the URL for MongoDB in accordance with your system.
  5. var url = "MongoDB ://localhost:27017/vehicle";

After fulfill the above three conditions, we should make connection to the database like this: MongoClient.connect(url, function(err,db){})

Then we have to make sure if there is any error or not with an if-else statement. If there is no error open a collection with its name.

var collection = db.collection('cars');

Now in the example below we have to drop this collection by using the function drop;

collection.drop(function(err,result){ })

Just like before we have to check for the error, if any. So to check if there is any error we use simple if-else statements.

The Object error will be passed by mongo itself and it will be false or null if there is no error, otherwise we will get an error object.

If we found an error we will console.log it, otherwise we will log the result of the query.

To make an optimum server to work smooth we should always close the connection after our use of it. There the last thing we do is close the db.

db.close();

JS code:

// require MongoDB 
var MongoDB  = require('MongoDB ');
var MongoClient = MongoDB .MongoClient;
//create url
var url = "MongoDB ://localhost:27017/vehicle";
//connect with mongo client
MongoClient.connect(url, function(err,db){

	if(err)
	{
		console.log(err);
	}
	else
	{
		console.log('Connected to ',url);
		// getting the reference of collection cars
		var collection = db.collection('cars');
		// to drop colection
		collection.drop(function(err,result){
		if(err)
		{
			console.log(err);
		}
		else
		{
			// result of query
			console.log(result);
		}
		db.close();
		});
	}

});

Output in console

MongoDB - Drop a collection

Server running

MongoDB - Drop a collection

MongoDB - Drop a collection

Here you can see there is no such collection name cars, exists now.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.