tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 No SQL > Mongo DB > How to remove all Documents in a Collection

How to remove all Documents in a Collection 

MongoDB is a scalable, high-performance, open source NoSQL database. It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation, MapReduce and Server-side JavaScript execution. This requires the library mongo-2.8.0.jar to be present in the classpath. The following example shows how to remove all documents in a Collection.

File Name  :  students.json

File Name  :  
com/bethecoder/tutorials/mongodb/tests/RemoveAllDocumentsTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.mongodb.tests;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class RemoveAllDocumentsTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    try {
      //Connect to mongoDB with given IP and PORT
      Mongo mongo = new Mongo("localhost"27017);
      
      //Get the database object
      DB database = mongo.getDB("mytestdb");
      
      //Gets a collection with a given name.
      DBCollection collection = database.getCollection("students");
      
      //List collection before update
      System.out.println("--- Collection Before Delete ---");
      listAll(collection);
      
      //Query with no conditions
      DBObject query = new BasicDBObject();

      //Remove all documents
      collection.remove(query);
      
      //List collection after update
      System.out.println("--- Collection After Delete ---");
      listAll(collection);
      
    catch (UnknownHostException e) {
      e.printStackTrace();
    catch (MongoException e) {
      e.printStackTrace();
    }
  }
  
  private static void listAll(DBCollection collection) {
    //Queries for all objects in this collection
    DBCursor dbCursor = collection.find();
    DBObject record = null;
    
    while (dbCursor.hasNext()) {
      record = dbCursor.next();
      System.out.println(record);
    }
  }
}
   

It gives the following output,
--- Collection Before Delete ---
{ "_id" : { "$oid" : "503cd20742e2e8031836ac53"} , 
	"name" : "Sriram" , "age" : 2}
{ "_id" : { "$oid" : "503cd20742e2e8031836ac54"} , 
	"name" : "Sudhakar" , "age" : 29 , "mobile" : "123456789"}
	
--- Collection After Delete ---



                    Print

   



Books Recommendation

 
 
bl  br