I want to delete all documents in 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 the correct way to do this?
I am using MongoDB 3.0.2
解决方案
To remove all documents use the 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());
}