使用API> = 3.0:
MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017);
MongoDatabase db = mongoClient.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());
要删除集合(文档和索引),您仍然可以使用:
db.getCollection("mainCollection").drop();
请参阅https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents
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());
}
If you want to remove all documents in collection then used below code :
db.getCollection("mainCollection").remove(new BasicDBObject());
Or If you want to drop whole collection then used this :
db.getCollection("mainCollection").drop();
对于较新的mongodb驱动程序,您可以使用FindIterable删除集合中的所有文档。
FindIterable<Document> findIterable = collection("mainCollection").find();
for (Document document : findIterable) {
collection("mainCollection").deleteMany(document);
}