java mongo exists,MongoDB 3 Java检查集合是否存在

I have the following problem:

I'm using the Java driver for MongoDB 3.

In version 2 it was possible to do DB.collectionExists(name) to check whether a collection exists in the selected database.

In version 3 with the switch from DB to MongoDatabase this method no longer exists.

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.

Thanks for your help

解决方案

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.

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 collectionNames = getCollectionNames();

for (final String name : collectionNames) {

if (name.equalsIgnoreCase(collectionName)) {

return true;

}

}

return false;

}

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.

As a result, go with your iteration over listCollectionNames approach.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值