EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Remove
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

MongoDB Remove

MongoDB Remove

Introduction to MongoDB Remove

  • MongoDB Remove method is implemented to remove any specific documents from a collection. This method is defined as db. collection.remove() structure code.
  • This remove() method provides a WriteResult() object which includes the status of the operation. After the success of the operation, the WriteResult() object includes info on the number of documents removed: WriteResult({“nRemoved”: 3}).
  • The method includes a query part which is required and other two optional parts such as justOne and writeConcern options included in the remove() method which delivers two different syntaxes for the MongoDB remove() method.
  • When we execute the remove() method applied on any collection in MongoDB database then, the writeResult object will return the status of the operation performed.

Syntax

The MongoDB Remove method includes two basic syntaxes implemented for removing any collection from MongoDB database described as follows:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax where the MongoDB remove() method takes a query document with an optional Boolean ‘justOne’ is:

Db.collection.remove(<query>, <justOne>)

And, syntax, where the MongoDB remove() method, takes a query document with an optional remove options document:

It is modified in version 5.0.,

Db.collection.remove(
<query>,
{justOne: <boolean>,
writeConcern: <document>,
let: <document> //supplemented in MongoDB 5.0
})

Let us explain the parameters used in the above syntaxes:

1. Query: It is a document type that states deletion criteria by means of query operators. This method removes all documents in a collection when we pass an empty document ({}).

2. justOne: It is Boolean type and optional one but is used for limiting the deletion operation to only a single document when set to true. The user should omit to use the value as false which is the default one and remove all documents which match the deletion criteria.

3. writeConcern: It is a document type that is optional where a document expresses the write concern. One should avoid applying the default write concern. The user should not set the write concern externally for the operation if executed in a transaction.

4. Collation: It is a document type that states the collation for using the operation. This collation permits users to define language-specific rules like rules for lettercase and accent marks for string comparison. This option specifies the below syntax:

Collation: {
Locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

While defining the collation, locale field is compulsory; whereas all other fields of collation are optional. If the collation is not stated but still the collection takes a default collation value which is specified for the collection when executed.

If a collection is stated with any collation or for the operations, then MongoDB applies the basic binary comparison implemented in preceding versions for the string comparisons.

For an operation, we cannot define many collations. Suppose, many collations per field cannot be defined, or maybe executing a find with a sort, one cannot apply one collation for the find and additional for the sort.
It is new in the MongoDB version 3.4.

5. Let: It is a document type parameter optionally defined. It states a document having a list of variables allowing the user for enhancing command readability through separation of variables from the query text. Its syntax has the below structure:

{<variable_name_1>: <expression_1>, ……., <variable_name_n>: <expression_n>}

The variable will be set to the value resulted by the expression which cannot be altered afterwards. For accessing the value of a variable present in the command, we will apply the double dollar sign prefix i.e. $$, together with having the variable name in the form $$<variable_name>. E.g. $$Totalsum.

It should be noted that to apply a variable to filter results, one must access the variable inside the $expr operator. It is new in version 5.0.

The MongoDB remove() method outputs an object which consists of the status of the operation. It results in a WriteResult object which includes the status of the operation.

How remove works in MongoDB?

Discussing the working of remove () method in MongoDB, we will illustrate the behavior of MongoDB Remove() method:

Write Concern:

The MongoDB remove() method implements the delete command that applies the default parameter i.e. writeConcern. But if we want to state a distinct write concern, then we must consist the write concern in the options parameter.

Query Considerations:

This remove() method will remove all documents by default which will match the query expression. We can define the justOne option for limiting the operation to remove just one document. Also, we can use the method findAndModify(), for deleting only a document sorted by a particular order.
When deleting multiple documents, this remove() method operation may incorporate additional read and/or write operations in MongoDB to the collection.

Capped Collections:

The MongoDB remove() method cannot be implemented with a capped collection.

Time Series Collections:

The MongoDB remove() method cannot be implemented on a time series collection.

Sharded Collections:

For a sharded collection, all remove() operations that define the justOne: true option must include the shard key or even the _id field on the query specification. Thus, the remove() operations stating justOne: true in a sharded collection that do not include either the _id field or the shard key result an error.

Transactions:

MongoDB remove method as, db.collection.remove(), can be implemented within multi-document transactions. If executed in a transaction, we must not externally set the parameter, write concern for the operation. We need to study some rules for applying the write concern with transactions.

Example

Let us illustrate some examples to view the working of this Mongo remove() method:
Suppose, we have a db ‘test’ and few collections created in it, where details of the collection named ‘Students’ is shown below:

use test
show collections
db.Students.find()

MongoDB Remove 1

Now, we will code to demonstrate how to remove any particular document from the collection.

Db.books.({_id:2)

When the above code is executed with success then it will remove the documents that have the student id as 2 generating the output as:

WriteResult({“nRemoved” : 1})
db.Students.find()

Output:

MongoDB Remove 2

Also, if we want to remove all documents from any collection, then call remove() having an empty query as, db.books.remove({}).

Conclusion

  • In MongoDB, we will use the remove() method to delete such documents from a specific collection which matches certain deleting criteria mentioning in the query function as parameters.
  • But to remove the entire documents of a collection, it may be more resourceful to implement the method as drop() that consists of indexes and after that we may reconstruct collection as well as restructure the collection indexes simply.

Recommended Articles

This is a guide to MongoDB Remove. Here we discuss the definition, How remove works in MongoDB? with examples respectively. You may also have a look at the following articles to learn more –

  1. MongoDB Join
  2. MongoDB Sharding
  3. MongoDB Users
  4. MongoDB Delete Collection
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (17 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (10 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more