MongoDB Remove Delete All Records Documents Java - Java @ Desk

Monday, May 19, 2014

MongoDB Remove Delete All Records Documents Java

MongoDB Remove Delete All Records Documents from a Collection in Java

In our last post, we understood MongoDB Remove Delete Record Document Java

What if we want to delete all the documents from a collection?

To implement this two strategies are there
1) Using a new instance of BasicDBObject class - Pass the new object of BasicDBObject to collection.remove() method to delete all the documents from a collection

2) Using DBCursor - DBCursor iterator is used to remove a documents from a collection using a Iterator

Refer example below

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoDBDelete {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");

  BasicDBObject document = new BasicDBObject();

  // Delete All documents from collection Using blank BasicDBObject
  collection.remove(document);

  // Delete All documents from collection using DBCursor
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   collection.remove(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}






No comments:

Post a Comment