如何使用MongoDB JAVA驱动程序从数据库中删除集合?

12

以下命令使用mongo.exe客户端输入(假设集合coll存在):

> use database
switched to db database
>db.coll.drop()
True

如何使用Mongo DB JAVA驱动程序执行db.coll.drop()?

2个回答

22

我认为这应该可以解决问题:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();

12

当前被接受的答案将会创建一个之前不存在的集合并删除它,因为如果指定的名称不存在,getCollection会创建一个集合。更高效的方法是先检查集合是否存在:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
if (db.collectionExists("myCollection")) {
    DBCollection myCollection = db.getCollection("myCollection");
    myCollection.drop();
}

3
你正在使用哪个版本的驱动程序?我正在使用3.3.0版本,但找不到collectionExists方法。 - Chris Sprague
我不知道当时我在使用什么......那个方法仍然存在于3.3和3.4中...这里是3.4的API文档:http://api.mongodb.com/java/3.3/com/mongodb/DB.html#collectionExists-java.lang.String- - Rondo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接