如何在Java中删除mongodb集合中的所有文档 [英] How to delete all documents in mongodb collection in java

查看:1388
本文介绍了如何在Java中删除mongodb集合中的所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除Java集合中的所有文档.这是我的代码:

I want to delete all documents in a collection in java. Here is my code:

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

这是正确的方法吗?

我正在使用MongoDB 3.0.2

I am using MongoDB 3.0.2

推荐答案

要删除所有文档,请使用BasicDBObject或DBCursor,如下所示:

To remove all documents use the BasicDBObject or DBCursor as follows:

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());
}

这篇关于如何在Java中删除mongodb集合中的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆