我想删除Java集合中的所有文档。这是我的代码:

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

这是正确的方法吗?

我正在使用MongoDB 3.0.2

最佳答案

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

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

关于java - 如何在Java中删除mongodb集合中的所有文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31058439/

10-09 06:08
查看更多