Question

Is there a way in the MongoDB Java driver to call the db.collection.remove(query) method that I see in the MongoDB shell documentation? That is, I know the exact criteria that I need to find all the documents I want to delete from MongoDB, but I can't find a way to make one call to remove those records in one trip. All that I can figure out is to find the documents and then delete them one by one.

I see this http://docs.mongodb.org/manual/reference/method/db.collection.remove/ which implies there should be a way to do it, but I can't figure out the Java calls to get me that to that call.

Thank you for your help

Was it helpful?

Solution

To remove documents with an age property of 25.

MongoClient mongo = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongo.getDB("thedb");
DBCollection collection = db.getCollection("test");

BasicDBObject query = new BasicDBObject();
query.append("age", 25);

collection.remove(query);

DBCollection and BasicDBObject are two of the most important classes in the Java API.

OTHER TIPS

Also to remove specific values from you document you can use following code with Mongo Java 3.2

Document docToDelete = new Document("Designation", "SE-1");
objDbCollection.findOneAndUpdate(new Document("Company", "StackOverflow"), new Document("$unset", docToDelete));

Above code will first find document having company = StackOverflow and then unset (remove) Designation = SE-1 key/value from that document.

Add and Update Mongo

public class App {
public static void main(String[] args) {

  try {

Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");

// get a single collection
DBCollection collection = db.getCollection("dummyColl");

//insert number 1 to 10 for testing
for (int i=1; i <= 10; i++) {
    collection.insert(new BasicDBObject().append("number", i));
}

//remove number = 1
DBObject doc = collection.findOne(); //get first document
collection.remove(doc);

//remove number = 2
BasicDBObject document = new BasicDBObject();
document.put("number", 2);
collection.remove(document);

//remove number = 3
collection.remove(new BasicDBObject().append("number", 3));

//remove number > 9 , means delete number = 10
BasicDBObject query = new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 9));
collection.remove(query);

//remove number = 4 and 5
BasicDBObject query2 = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(5);
query2.put("number", new BasicDBObject("$in", list));
collection.remove(query2);

//print out the document
DBCursor cursor = collection.find();
    while(cursor.hasNext()) {
         System.out.println(cursor.next());
    }

    collection.drop();

    System.out.println("Done");

  } catch (UnknownHostException e) {
e.printStackTrace();
  } catch (MongoException e) {
e.printStackTrace();
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top