如何在java中删除mongodb集合中的所有文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31058439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete all documents in mongodb collection in java
提问by Viratan
I want to delete all documents in a collection in java. Here is my code:
我想删除java集合中的所有文档。这是我的代码:
MongoClient client = new MongoClient("10.0.2.113" , 27017);
MongoDatabase db = client.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());
Is this the correct way to do this?
这是正确的方法吗?
I am using MongoDB 3.0.2
我正在使用 MongoDB 3.0.2
采纳答案by chridam
To remove all documents use the BasicDBObject or DBCursor as follows:
要删除所有文档,请使用 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());
}
回答by Yogesh
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();
回答by hawkpatrick
Using API >= 3.0:
使用 API >= 3.0:
MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017);
MongoDatabase db = mongoClient.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());
To drop the collection (documents andindexes) you still can use:
要删除集合(文档和索引),您仍然可以使用:
db.getCollection("mainCollection").drop();
see https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents
见https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents
回答by invzbl3
For newer mongodb drivers you can use FindIterableto remove all documents in collection.
对于较新的 mongodb 驱动程序,您可以使用FindIterable删除集合中的所有文档。
FindIterable<Document> findIterable = collection.find();
for (Document document : findIterable) {
collection.deleteMany(document);
}