MongoDB Remove Delete Record Document Java - Java @ Desk

Monday, May 19, 2014

MongoDB Remove Delete Record Document Java

MongoDB Remove Delete Record Document from a Collection in Java

In our last post, we explained how to remove/delete a record/document from a collection in MongoDB from command line

This post provides a sample example to implement the delete functionality for a record or document from a collection in Java

For example, we want to delete a record of a Loan where name = "Personal Loan" from a Loans collection.

To implement this following things are followed in order :
1) Create a DB object
2) Load a collection "loans"
3) Create BasicDBObject object
4) Remove BasicDBObject object from collection object created in step 2

Click here to see MongoDB Remove Delete All Records Documents Java

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
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();
  document.put("name", "Personal Loan");
  
  WriteResult result = collection.remove(document);
  System.out.println("Number of documents deleted : " + result.getN());
 }
 
 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}


Click here to see MongoDB Remove Delete All Records Documents Java





No comments:

Post a Comment