How to delete all documents in mongodb collection in java

I want to delete all documents from a collection in java. Here is my code:

MongoClient client = new MongoClient("10.0.2.113" , 27017); MongoDatabase db = client.getDatabase("maindb"); db.getCollection("mainCollection").deleteMany(new Document()); 

Is this being done right?

I am using MongoDB 3.0.2

+16
java mongodb mongodb-java
source share
4 answers

To delete all documents, use BasicDBObject or DBCursor as follows:

 MongoClient client = new MongoClient("10.0.2.113" , 27017); MongoDatabase db = client.getDatabase("maindb"); MongoCollection collection = db.getCollection("mainCollection") BasicDBObject document = new BasicDBObject(); // Delete All documents from collection Using blank BasicDBObject collection.deleteMany(document); // Delete All documents from collection using DBCursor DBCursor cursor = collection.find(); while (cursor.hasNext()) { collection.remove(cursor.next()); } 
+15
source share

Using API> = 3.0:

 MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017); MongoDatabase db = mongoClient.getDatabase("maindb"); db.getCollection("mainCollection").deleteMany(new Document()); 

To delete a collection (documents and ), you can still use:

 db.getCollection("mainCollection").drop(); 

see https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents

+17
source share

If you want to delete all documents in the collection, then use the code below:

  db.getCollection("mainCollection").remove(new BasicDBObject()); 

Or If you want to delete the entire collection, then use this:

 db.getCollection("mainCollection").drop(); 
+6
source share

For newer mongodb drivers, you can use FindIterable to delete all documents in the collection.

 FindIterable<Document> findIterable = collection.find(); for (Document document : findIterable) { collection.deleteMany(document); } 
0
source share

All Articles