且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中删除mongodb集合中的所有文档

更新时间:2023-02-14 08:21:19

要删除所有文档,请使用BasicDBObject或DBCursor,如下所示:

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());
}