Node.js – Delete Collection in MongoDB
In Node.js, deleting a MongoDB collection means dropping the collection itself from the database. The correct MongoDB operation for this is drop(). If you use remove() or deleteMany({}), you delete documents inside the collection, but the collection still exists.
In this Node.js Tutorial, we shall learn to delete a collection in MongoDB from a Node.js application. We shall also see the difference between dropping a collection and deleting all documents from a collection, because both are common search intents for this topic.
Node.js MongoDB delete collection: drop() vs remove()
The original MongoDB driver code in older tutorials often uses collection.remove({}). That operation removes matching documents. It does not drop the collection metadata, indexes, or collection name. To delete the collection itself, use collection.drop() or db.dropCollection(collectionName).
| Node.js MongoDB operation | What it does | When to use it |
|---|---|---|
collection.drop() | Drops the collection from the database. | Use when the collection itself must be removed. |
db.dropCollection("users") | Drops the named collection from the database. | Use when you have the database object and the collection name. |
collection.deleteMany({}) | Deletes all documents, but keeps the collection. | Use when the collection and indexes should remain. |
collection.remove({}) | Older API style for removing documents. | Avoid in new code; prefer deleteMany(). |
You can refer to the official MongoDB db.collection.drop() documentation and the MongoDB Node.js driver guide for databases and collections for the current driver behavior.
Steps to delete a MongoDB collection from Node.js
Following is a step by step guide with an example to delete a collection in MongoDB from Node.js Application.
Step 1: Start MongoDB Service.
Run the following command to start MongoDB Service.
sudo service mongod start
Step 2: Get the base URL to MongoDB Service.
A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.
arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
While the Mongo Shell starts up, it echoes back the base url of MongoDB.
mongodb://127.0.0.1:27017
Step 3: Prepare the complete URL.
Append the Database name you want to connect to (say newdb), to the base URL.
mongodb://127.0.0.1:27017/newdb
Step 4: Create a MongoClient.
var MongoClient = require('mongodb').MongoClient;
Step 5: Make connection from MongoClient to the MongoDB Server with the help of URL.
MongoClient.connect(url, <callback_function>);
Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.
If the connection is successful, the db object points to the database, newdb.
Step 6: Get reference to MongoDB Collection.
db.collection(<collection_name>, <callback_function>);
Once you get db object that points to the specified mongodb database, use it to get reference to required collection using the above statement.
Step 7: Delete MongoDB Collection.
Following is the syntax of remove() method used to delete collection in MongoDB from Node.js.
collection.remove({},callback_function)
where
| collection | reference to the mongodb collection that we would like to delete |
| callback_function | This Node.js Callback Function is called after Node has tried deleting the specified collection, and ready with the result. The callback function receives error and result object as arguments. |
Note: The above older syntax removes documents from the collection. For a real collection drop, use the updated drop() examples below.
Example 1 – Delete Collection in MongoDB using Node.js
In this example, we will delete a MongoDB Collection using remove() method.
node-js-mongodb-delete-collection.js
// example : delete 'users' collection in newdb database
var url = "mongodb://localhost:27017/newdb";
// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;
// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// db pointing to newdb
console.log("Switched to "+db.databaseName+" database");
// get reference to collection
db.collection("users", function(err, collection) {
// handle the error if any
if (err) throw err;
// delete the mongodb collection
collection.remove({}, function(err, result){
// handle the error if any
if (err) throw err;
console.log("Collection is deleted! "+result);
// close the connection to db when you are done with it
db.close();
});
});
});
Output
~$ node node-js-mongodb-delete-collection.js
Switched to newdb database
Collection is deleted! {"n":0,"ok":1}
The output shows that the command ran successfully, but this older code is deleting documents that match the empty filter {}. It is not the preferred way to drop the collection in current Node.js MongoDB code.
Current Node.js MongoDB example using collection.drop()
For new Node.js applications, install the MongoDB driver and use MongoClient with async and await. The following example drops the users collection from the newdb database.
npm install mongodb
drop-users-collection.js
const { MongoClient } = require('mongodb');
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('newdb');
const result = await db.collection('users').drop();
console.log(`Collection dropped: ${result}`);
} catch (err) {
if (err.codeName === 'NamespaceNotFound') {
console.log('Collection does not exist.');
} else {
throw err;
}
} finally {
await client.close();
}
}
run().catch(console.error);
Run the script from the terminal.
node drop-users-collection.js
When the collection exists and is dropped successfully, the result is usually true.
Collection dropped: true
Delete all documents but keep the MongoDB collection in Node.js
If your goal is to clear the collection while keeping its indexes and collection name, do not use drop(). Use deleteMany({}) with an empty filter to delete all documents in that collection.
const { MongoClient } = require('mongodb');
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('newdb');
const result = await db.collection('users').deleteMany({});
console.log(`Deleted documents: ${result.deletedCount}`);
} finally {
await client.close();
}
}
run().catch(console.error);
This is safer when the application expects the collection to continue existing after the cleanup operation.
Delete one MongoDB collection by name with db.dropCollection()
You can also drop a collection from the database object by passing the collection name to dropCollection(). This is convenient when the collection name is stored in a variable.
const collectionName = 'users';
const result = await db.dropCollection(collectionName);
console.log(`Dropped ${collectionName}: ${result}`);
Use this only after validating the collection name. Avoid passing unchecked user input directly into a drop operation.
Node.js MongoDB collection deletion checklist
- Confirm whether the requirement is to drop the collection or only delete documents inside it.
- Back up important data before running
drop()ordeleteMany({}). - Use the correct database name in the MongoDB connection string or
client.db(). - Handle the case where the collection does not exist, especially in deployment scripts.
- Close the MongoDB client in a
finallyblock to avoid open connections. - Do not build collection names directly from untrusted user input.
MongoDB collection drop reference links for Node.js
MongoDB Tutorial – Learn MongoDB from basics with Examples.
- MongoDB Manual: db.collection.drop()
- MongoDB Node.js Driver: Databases and Collections
- Node.js MongoDB Tutorial
FAQs on deleting a MongoDB collection with Node.js
How do I delete a MongoDB collection in Node.js?
Use await db.collection('collectionName').drop() or await db.dropCollection('collectionName'). Both operations remove the collection from the database.
Does collection.remove({}) delete the collection in MongoDB?
No. collection.remove({}) removes matching documents in older driver code. It does not drop the collection itself. In new code, use deleteMany({}) to delete documents or drop() to drop the collection.
What happens if I drop a MongoDB collection that does not exist?
The operation can return an error such as NamespaceNotFound. Handle this case in your Node.js code if the collection may already be missing.
Should I use drop() or deleteMany({}) in Node.js MongoDB code?
Use drop() when the collection should be removed. Use deleteMany({}) when you want to remove all documents while keeping the collection available for future inserts.
Does dropping a MongoDB collection remove indexes?
Yes. Dropping a collection removes the collection and its indexes. If you only want to clear documents while preserving indexes, use deleteMany({}) instead.
Node.js MongoDB collection deletion summary
In this Node.js MongoDB tutorial : Node.js – Delete Collection in MongoDB, we have learnt how to remove MongoDB collection data from a Node.js application. For deleting the collection itself, use collection.drop() or db.dropCollection(). For deleting only the documents inside the collection, use deleteMany({}). In our next tutorial – Node.js Insert Document to MongoDB Collection, we shall learn to insert one or more documents to a MongoDB collection.
TutorialKart.com