mongodb remove operation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Previously we have seen find, insert, update and upsert operations, this article will deal with mongodb remove operation.

MongoDB Remove Operation

As name suggests, mongodb remove operation is used to perform deletion of documents from a collection. It can remove one or more documents based on the collection provided. The syntax for the same as per official documentation is as below.

  • db is a variable which refers to current database selected.
  • collection is the collection on which we are going to perform remove operation
  • <query> is the query criteria for deletion of records
  • <justOne> is boolean and OPTIONAL attribute which tells to delete only one matching document

Example

Let us see an example of mongodb insert operation. Before that let us see what data we have in collections.

Now let us try to remove documents whose salary is less than 50000.

So according to syntax of mongodb remove operation, our query becomes,

Run this query and it will return the result as WriteResult({ "nRemoved" : 3 })  which means mongodb remove operation as succeeded in deleting three documents.

Now again check the remaining documents using db.employees.find(); It will return below

Now let us write a mongodb remove operation using justOne option. We have 2 employees with age 25.

Note that value is same as specifying true. It will remove only one document. Run the query and you will get result as  WriteResult({ "nRemoved" : 1 })

You can find remaining documents just to confirm.

I hope this article helped understand the mongodb remove operation. These articles were just an overview of mongodb operations. Our main goal is to perform these operations from java. We will see them from next article onwards.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Leave a Reply

Your email address will not be published. Required fields are marked *