繁体   English   中英

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

[英]How to delete all documents in mongodb collection in java

我想删除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

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

要删除所有文档,请使用 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());
}

如果要删除集合中的所有文档,请使用以下代码:

 db.getCollection("mainCollection").remove(new BasicDBObject());

或者如果你想删除整个集合然后使用这个:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM