2015-06-25 38 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

相关问题