![](/img/trans.png)
[英]Matlab delete all documents from MongoDB collection via Java driver
[英]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.