11.1. Deleting Documents in MongoDB: Introduction to Deleting Documents in MongoDB
Page 55 | Listen in audio
Deleting Documents in MongoDB: An Introduction
MongoDB is a document-oriented NoSQL database system that offers high performance, high availability and easy scalability. It works on the concept of collections and documents, instead of tables and rows as in relational databases. In this section, we will understand how to delete documents in MongoDB.
Why Delete Documents?
There are several reasons to delete documents in a MongoDB database. The data may no longer be needed, out of date, or irrelevant to the current analysis. In all these cases, deleting documents is a crucial operation. Additionally, deleting unnecessary documents can improve database efficiency and performance.
Delete Documents in MongoDB
To delete documents in MongoDB, we use the remove()
method. This method removes documents from a collection. The basic syntax of remove()
in MongoDB is db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
.
Document Deletion Example
Suppose we have a collection called 'students' with the following documents:
{ "_id": ObjectId("5f9b1b2f8f161178fed8d0f1"), "name": "John", "age": 22, "subjects": ["Math", "English", "Science"] }, { "_id": ObjectId("5f9b1b2f8f161178fed8d0f2"), "name": "Jane", "age": 23, "subjects": ["English", "History", "Geography"] }, { "_id": ObjectId("5f9b1b2f8f161178fed8d0f3"), "name": "Bob", "age": 24, "subjects": ["Math", "Physics", "Chemistry"] }
To delete the document where the name is 'John', we use the following command:
db.students.remove({"name":"John"})
This command removes the document where the 'name' field is 'John'.
Deleting Multiple Documents
We can delete multiple documents at once in MongoDB. To do this, we pass an exclusion criteria that corresponds to several documents. For example, to delete all documents where the age is less than 24, we use the following command:
db.students.remove({"age": {"$lt": 24}})
This command removes all documents where the 'age' field is less than 24.
Deleting All Documents from a Collection
To delete all documents from a collection, we pass an empty document {} as the exclusion criteria. For example, to delete all documents from the 'students' collection, we use the following command:
db.students.remove({})
This command removes all documents from the 'students' collection.
Conclusion
Deleting documents is a fundamental operation in MongoDB. It is important to remember that deleting documents is an operation that must be carried out with care, as once a document is deleted, it cannot be recovered. Therefore, it is always a good practice to back up your data before performing deletion operations.
Now answer the exercise about the content:
_What is the function of the remove() method in MongoDB?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: