如何使用 Mongo DB JAVA 驱动程序从 MongoDB 中的数据库中删除集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19498650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to drop collection from database in MongoDB using Mongo DB JAVA driver?
提问by rok
The following commands were typed using mongo.exe client (assuming that the collection collexists) :
以下命令是使用 mongo.exe 客户端输入的(假设集合coll存在):
> use database
switched to db database
>db.coll.drop()
True
How to perform db.coll.drop() using Mongo DB JAVA driver?
如何使用 Mongo DB JAVA 驱动程序执行 db.coll.drop()?
采纳答案by amazia
I think this should work:
我认为这应该有效:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();
回答by Rondo
The current accepted answer would create a collection that did not previously exist and delete it, since getCollection creates one by the given name if it does not exist. It would be more efficient to check for existence first:
当前接受的答案将创建一个以前不存在的集合并将其删除,因为 getCollection 如果不存在则按给定名称创建一个集合。首先检查是否存在会更有效:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("mydb");
if (db.collectionExists("myCollection")) {
DBCollection myCollection = db.getCollection("myCollection");
myCollection.drop();
}