Search code examples
javamongodbmongodb-java

Use MongoDB db.collection.remove(query) in java


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


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.