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


db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

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
    
    db.car.remove({})
    

    It produces following output:

    
    WriteResult({ "nRemoved" : 6 })
    

    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.
    
    >db.car.remove( {speed : {$lt:45}})
    

    Output:

    
    WriteResult({ "nRemoved" : 2 })
    

    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.
    
    db.car.remove( { speed: {$gt:51}},1)
    

    Output:

    
    WriteResult({ "nRemoved" : 1 })
    

    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.
    
    db.car.remove( { speed: { $gt:30 }, $isolated:1 })
    

    Output:

    
    WriteResult({ "nRemoved" : 8 })
    

    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.

    
    package com.journaldev.mongodb;
    import java.net.UnknownHostException;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBObject;
    import com.mongodb.MongoClient;
    import com.mongodb.WriteResult;
    public class MongoDBRemove {
    	public static void removeByQuery() throws UnknownHostException {
    		// Get a new connection to the db assuming that it is running
    		MongoClient m1 = new MongoClient();
    		// use test as a database,use your database here
    		DB db = m1.getDB("test");
    		// fetch the collection object ,car is used here,use your own
    		DBCollection coll = db.getCollection("car");
    		// builds query for car whose speed is less than 45
    		BasicDBObject b1 = new BasicDBObject("speed", new BasicDBObject("$lt",
    				45));
    		// invoke remove method
    		WriteResult c1 = coll.remove(b1);
    		// print the number of documents using getN method
    		System.out.println("Number of documents removed:" + c1.getN());
    	}
    	public static void removeSingleDoc() throws UnknownHostException {
    		MongoClient m1 = new MongoClient();
    		DB db = m1.getDB("test");
    		DBCollection coll = db.getCollection("car");
    		BasicDBObject b1 = new BasicDBObject("speed", new BasicDBObject("$gt",
    				45));
    		// invoke findOne so that the first document is fetched
    		DBObject doc = coll.findOne(); // get first document
    		// remove the document fetched using findOne method
    		WriteResult r1 = coll.remove(doc);
    		System.out.println("------------------------------------");
    		System.out.println("Number of documents removed:" + r1.getN());
    	}
    	public static void removeAllDocs() throws UnknownHostException {
    		MongoClient m1 = new MongoClient();
    		DB db = m1.getDB("test");
    		DBCollection coll = db.getCollection("car");
    		// remove all documents in the collection with empty object
    		WriteResult r1 = coll.remove(new BasicDBObject());
    		System.out.println("------------------------------------");
    		System.out.println("Number of documents removed:" + r1.getN());
    	}
    	public static void main(String[] args) throws UnknownHostException {
    		// invoke all the methods to perform remove operation
    		removeByQuery();
    		removeSingleDoc();
    		removeAllDocs();
    	}
    }
    

    Output of the above program is:

    
    Number of documents removed:0
    ------------------------------------
    Number of documents removed:1
    ------------------------------------
    Number of documents removed:4
    

    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

%d bloggers like this: