MongoDB 3 Java检查集合是否存在 [英] MongoDB 3 Java check if collection exists
问题描述
我遇到以下问题:
我正在使用MongoDB 3的Java驱动程序。
I'm using the Java driver for MongoDB 3.
在版本2中,可以执行DB.collectionExists(name)来检查所选数据库中是否存在集合。
In version 2 it was possible to do DB.collectionExists(name) to check whether a collection exists in the selected database.
在版本3中从DB切换到MongoDatabase此方法不再存在。
In version 3 with the switch from DB to MongoDatabase this method no longer exists.
如何确定数据库中是否存在集合?我尝试使用listCollectionNames()迭代集合,但这似乎非常无效。
How do I find out whether a collection exists inside a database? I tried to iterate over the collections with listCollectionNames() but this seems quite ineffective.
感谢您的帮助
推荐答案
你是对的。似乎3.0.x版本的MongoDB驱动程序没有将<收集存在?方法移植到 MongoDatabase
。
You are correct. It appears as if the 3.0.x version of MongoDB driver did not port over a direct "does collection exist?" method to MongoDatabase
.
正如您已经提到的,一个选项是迭代 listCollectionNames()
的结果。虽然这似乎无效,但它非常类似于 DB.collectionExists(String)
方法的实现。下面的代码片段是从 DB.java 类中复制而来的。 nofollow noreferrer> mongo-java-driver source :
As you already mentioned, one option for you is to iterate through the results of listCollectionNames()
. While this seems ineffective, it is very similar to what the implementation of the DB.collectionExists(String)
method does. The code snippet below was copied from the DB.java
class in mongo-java-driver source:
public boolean collectionExists(final String collectionName) {
Set<String> collectionNames = getCollectionNames();
for (final String name : collectionNames) {
if (name.equalsIgnoreCase(collectionName)) {
return true;
}
}
return false;
}
您还可以获得 DB $ c $通过调用
中取代 getDB
MongoClient MongoDatabase
>方法。这使您可以访问 collectionExists
方法,已弃用。当然,我不推荐第二种方法,因为如上所述,已弃用。
You could also get DB
instead of MongoDatabase
from the MongoClient
by calling the getDB
method. That gives you access to the collectionExists
method which is deprecated. Of course, I do not recommend this second approach because, as mentioned, it is deprecated.
作为结果,在 listCollectionNames
方法上进行迭代。
As a result, go with your iteration over listCollectionNames
approach.
这篇关于MongoDB 3 Java检查集合是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!