2015-06-25 104 views
8

我想刪除java中集合中的所有文檔。這裏是我的代碼:如何刪除java中的mongodb集合中的所有文檔

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

這是正確的方法嗎?

我使用MongoDB的3.0.2

+0

要刪除特定匹配的文件或刪除整個集合? – Yogesh

+0

集合中的所有文檔。 – Viratan

回答

8

要刪除所有文件使用BasicDBObject或DBCursor如下:

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

BasicDBObject document = new BasicDBObject(); 

// Delete All documents from collection Using blank BasicDBObject 
collection.remove(document); 

// Delete All documents from collection using DBCursor 
DBCursor cursor = collection.find(); 
while (cursor.hasNext()) { 
    collection.remove(cursor.next()); 
} 
+1

謝謝你,是我想要的 – Viratan

+0

@Viratan不客氣。 – chridam

+0

這兩種方法有什麼區別? –

4

如果你想刪除集合中的所有文件,然後使用下面的代碼:

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

,或者如果你想刪除整個集合,然後用這個:

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

如果要繼續使用它,建議不要使用drop()截斷集合。您可能會收到一個錯誤的錯誤'操作中止,因爲:集合上的所有索引都被刪除'。這顯然是因爲索引銷燬是異步的。 – Wheezil

相關問題