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

25

我想在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


你想要删除特定匹配的文档还是删除整个集合? - Neo-coder
集合中的所有文档。 - Viratan
4个回答

28

使用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


21

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

这两种方法有什么区别? - Abhishek Singh

10
如果您想从集合中删除所有文档,则可以使用以下代码:
 db.getCollection("mainCollection").remove(new BasicDBObject());

或者,如果您想要删除整个集合,请使用以下方法:

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

2
如果您打算继续使用集合,请勿使用drop()截断集合。 您可能会收到错误信息:“操作中止,原因是:集合上的所有索引都已删除”。 这显然是因为索引销毁是异步的。 - Wheezil

0

对于较新的mongodb驱动程序,您可以使用FindIterable来删除集合中的所有文档。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接