MongoDB remove example using Mongo Shell and Java Driver

MongoDB remove method removes a single document or all the documents present in the collection or the documents with specific criteria.

The syntax for remove is

query: specifies the documents to be removed from the collection.

justOne: boolean parameter with value true that limits the deletion to a single document.

writeConcern: guarantees the reporting on success of a write operation.

This method returns the object that contains the status of write operation indicating the number of documents that have been removed successfully.

Consider the following examples for remove method:

  1. To remove all documents in a collection: invoke remove method with an empty query document as

    It produces following output:

    This removes all the documents present in the collection car and provides the output indicating that 6 records were removed.
  2. To remove the documents that match the criteria entered by the user: call remove method specifying the query parameter.

    Output:

    This deletes the documents in the car collection having speed less than 45 and notifies in the output that two documents were removed from the collection.
  3. To remove a single document that match the criteria entered: invoke remove method with query criteria and set justOne parameter to 1 or true.

    Output:

    This removes the first document in the car collection whose speed is greater than 51 and indicates that 1 record is removed from the collection.
  4. The $isolated :1 isolates the query as specified in the parameter. By using the $isolated option, we can ensure that no client sees the changes until the operation completes or errors out.

    Output:

    This removes the documents in the car collection whose speed is greater than 20 and since isolation is set to 1 the operation is atomic which means none of the users will be able to see this change until the whole set of operation is completed.

    MongoDB Remove Java Program

    In this section let’s write a java program to delete the documents from the collection.

    Output of the above program is:

    That’s all for removing documents from a collection in MongoDB, we will look into more MongoDB features in coming posts.

By admin

Leave a Reply