Delete a collection in a MongoDB database
In this article, we will discuss the issue of deleting a collection in MongoDB in detail and explain the different methods and queries used to delete a collection in MongoDB.
MongoDB delete collection
There are two ways to delete a collection in MongoDB; After executing the drop command in the MongoDB database server, the output will be true or false. If the collection exists in the database and will be deleted successfully, the result will be true.
If the collection does not exist in the database and cannot be appropriately deleted, the result will be false.
Use the drop and remove methods to remove a collection from MongoDB. When unloading a collection, you must also specify the collection name.
Using the drop() method
To remove a collection from a MongoDB database, use db.collection.drop()
the remove function. It removes a collection from the database and deletes any associated indexes.
-
db.collection.drop()
The drop function and the drop command generate an invalidation event for any change streams opened on the dropped collection. -
db.collection.drop()
The drop method and the drop command stop ongoing index builds on the target collection before dropping the target collection. Prior to MongoDB 4.4, attempting to dump a collection with an ongoing index build resulted in an error, but the collection was not dropped.Aborting a primary index build does not cancel secondary index builds for a replica set or shard replica set. Instead, MongoDB attempts to stop the ongoing build of the specified index on the primary node and, if successful, generates an abort oplog entry.
A secondary member with an ongoing build for replication waits for the primary member to commit or abort the oplog entry before committing or aborting the index build.
- Starting in MongoDB 4.0.2, deleting a collection deletes the region/tag scope for the connection.
- Starting in MongoDB 5.0, if you attempt to drop a collection in the admin or config database from a mongos, the drop command and the db.collection.drop() method will return an error. Connect to the config server and run commands to drop these collections instead.
grammar:
db.collection_database.drop()
The collection database is specified in the above syntax as the name of the collection to be removed from the database server.
Using the remove() method
To remove a document from a collection, use db.collection.remove()
the function.
grammar:
db.collection_database.remove ({})
The collection database is defined in the previous syntax as the location from which the documents have to be removed. So, if you provide an empty result set to the remove method ()
, it will remove all the collection records.
db.collection_name.remove (<query>, {Writeconcern, justone})
Query parameters are defined as the ability to remove a single item from a collection based on a query parameter.
There is only one parameter defined, which removes a document from a collection. It must be enabled by setting the keyword to true.
After using true keyword in selection criteria, only one record is eliminated. If you do not use true keyword in our selection criteria, you will delete all the articles in the collection.
When using Writeconcern, the default use of writeconcern is bypassed.
remove()
Method parameters:
- query - The query operator is used to provide the deletion conditions. For example, passing an empty document() will delete all documents in the collection.
- justOne - If set to true, deletion will be limited to just one document. Without using the false default value, all documents matching the deletion criteria will be deleted.
- writeConcern - A document expressing the written concern. Omitting writeconcern defaults.
Deleting a collection in MongoDB
If you want to delete the entire collection and its indexes, you can use the drop method to drop any collection including its indexes from the database. The drop method will delete the collection and its indexes from the database server.
Using the remove method, you can remove certain documents from a collection. The remove method removes all documents from a collection, but the index remains on the database server and is not deleted.
After deleting a collection from the database server, two result sets are displayed.
- True
- False
The following query demonstrates that when a collection is deleted from the database server, the result set will display a true value. For example, the following query results in true.
The result set will show true because the database server has deleted the collection.
show collections
db.test1.drop()
show collections
The above query will result in false. The output in the result set will be false because the collection has not been deleted from the database server or does not exist in the database.
You must first connect to the database in question before you can delete a collection from it. If you are not connected to or have access to the specified database, the collection will not be deleted.
The following query demonstrates how to utilize the specified database before deleting a collection from the database.
db.col_stat.drop()
use test
db.col_stat.drop()
show collections
Now, let's discuss the sample queries for remove and drop methods.
Use the drop() method to delete a collection.
First, use the command show dbs to view a list of accessible databases.
If you want to delete the new database mydb>, use dropDatabase()
the command.
Database list.
Remove all documents from a collection using the remove() method.
Consider the following data from the mycol dataset.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
The following example will delete all records using the MongoDB Overview.
Delete only one
If there are many records and you want to remove the first record, use justOne option in remove() function.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Delete All Documents
If no delete conditions are specified, MongoDB will delete the entire document from the collection. This is the counterpart to the SQL Truncate command.
db.mycol.find()
Nothing will be displayed afterwards, as all data has been deleted from the database.
Deleting a MongoDB database using the command line
The easiest way to delete a Mongo database is to run the mongo shell command from the command line, using the relevant flags and parameters to tell the mongo shell that you want to delete the database.
The most basic mongo shell command can be used to instantly connect to a specific database. In this example, it is used to connect to the database bookstore from our server’s bash prompt.
$ mongo bookstore
MongoDB shell version: 3.0.9
connecting to: bookstore
Instead of connecting to our bookstore database and executing commands from the mongo shell, you can provide the eval flag followed by the JavaScript code you want MongoDB to execute. Our database can be easily dumped in one line.
You want to drop the database in this case; therefore, you will use the db.dropDatabase() function to destroy the database you are connected to. Although it is not required, you will wrap this method with the printjson function to ensure that the output of this command is meaningful and easy to understand.
You don't need heredocs or eval, mongo can act as an interpreter.
var db = new Mongo().getDB("someDatabase");
db.dropDatabase();
This article explains how to use the drop method; you can delete a collection and its indexes, and using the remove method; you can remove single or all documents from a collection.
If the collection exists in the database, the result set will display the result as true, otherwise false output is displayed. Also, it is explained to delete or remove a collection in MongoDB using the command line.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato
Sort a collection by date in MongoDB
Publish Date:2025/04/11 Views:64 Category:MongoDB
-
In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB
Counting records in MongoDB
Publish Date:2025/04/11 Views:146 Category:MongoDB
-
This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha
Pretty printing in MongoDB
Publish Date:2025/04/11 Views:150 Category:MongoDB
-
This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho
MongoDB Adding Elements to an Array
Publish Date:2025/04/11 Views:136 Category:MongoDB
-
This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values to an array The $push operator is one of the various array update operators provided by MongoDB
MongoDB Search by ID
Publish Date:2025/04/11 Views:131 Category:MongoDB
-
The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n
MongoDB starts with a query
Publish Date:2025/04/10 Views:195 Category:MongoDB
-
In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t