MongoDB 3 Java check if collection exists

mongodb check if collection exists
mongodb check if document exists java
mongodb create collection if not exists
mongodb drop collection if exists java
check if document exists in mongodb python
mongodb check if database exists node js
access mongodb collection
mongoose check if document exists

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<String> 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.

MongoDB 3 Java check if collection exists, 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  In MongoDB 3.0 and later, you have to run a command to list all collections in a database: use test; db.runCommand( { listCollections: 1 } ); Although querying system.namespaces will still work when you use the default storage engine (MMAPv1), it is not guaranteed to work for other engines, such as WiredTiger.

One alternative is to use the MongoIterable.into function to add these to a target ArrayList that you can call contains("collectionName") on.

boolean collectionExists = client.getDatabase("dbName").listCollectionNames()
    .into(new ArrayList<String>()).contains("collectionName")

How to check if an Collection exists? - help, xvendo February 18, 2016, 5:25am #3 The actual mongodb collection isn't created until you insert some data, but that doesn't stop ://blog.serverdensity.​com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/. 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.

for anyone still looking: Assuming you have MongoDatabase instance called "db"

try {
        db.createCollection("myCol");
    } catch (MongoCommandException e) {
        System.err.println("Collection Exists");
    }

How to check whether a Collection exists, No SQL > Mongo DB > How to check whether a Collection exists com/​bethecoder/tutorials/mongodb/tests/CollectionExistanceTest.java. Author : Sudhakar KV. 5 MongoDB Java Program for exists operations Exists operator set to true This operation returns only the documents that contain the field specified in the query.

I came across this post as I was trying to find out an efficient way to check if a collection exists. As I have more than 50k Collections in my database, using the listCollectionNames() method is extremely inefficient.

What I did was to use the db.collection.count() method and if it returned a non-zero value, then I would treat it as a non-existent collection. Ofcourse this is not hundred percent correct, since one could have a collection with zero entries and this approach would treat that as a non-existent collection. But for most scenarios in MongoDB, a collection makes sense only if it has at least one document. Following is a sample code,

public boolean isCollectionExists(DB db, String collectionName) 
{

    DBCollection table = db.getCollection(collectionName);
    return (table.count()>0)?true:false;
}

MongoDB exists example using Mongo Shell and Java Driver , Let's check out the examples of usage of exists operator. 2 Exists operator set to true and selection criteria specified; 3 Exists operator set to false; 4 Retrieve documents having null values; 5 MongoDB Java Program for exists operations the speed field and the speed greater than 80 are retrieved from the collection. Server: Ubuntu 14.04 with MongoDB 3.2 Client: Mac OS X 10.9 with Java Driver version 3.2 (Java 8) Description Called "db.createCollection(COLLECTION_LOGS, options)" throws "CommandFailureException" because COLLECTION_LOGS already exists.

MongoIterable <String> collection =  database.listCollectionNames();
    for(String s : collection) {
        if(s.equals("collectionName")) {
            return true;

        }
    }
    return false;
}

Databases and Collections, If a database does not exist, MongoDB creates the database when you first store data for that database. The following example accesses the test database: Which version of MongoDB are you using, this getCollectionNames() exists in MongoDB 3.0 – Roberto Feb 23 '17 at 21:07 3 Dude, the latest node driver for mongo is 2.2 (link) . 3.0 does not even exist.

Get Database Information and Check if a MongoDB Collection Exists , 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  Updating pre-existing documents in mongoDB java driver when you've changed document structure 0 How can I check if particular value exists using Java driver 3.6+ mongodb?

[JAVA-2079] collectionExists returns false although collection really , The PyMongo Python driver for MongoDB must be installed along with Python Version 3. Prerequisites. The MongoDB server must be running on  The db.getCollection() object can access any collection methods. The collection specified may or may not exist on the server. If the collection does not exist, MongoDB creates it implicitly as part of write operations like db.collection.insertOne().

$exists, In the Exception handler the call to "collectionExists" returns false, but the collection really exists: // Double check if (!db. Tomcat server that communicate over the MongoDB. I used MongoDB 2.6 through to 3.0.8 with Java driver version 2.12.2 0 Vote for this issue. Watchers: 3 Start watching this issue  MongoDB Manual. Version 4.2 (current) Starting in MongoDB 4 This query will select all documents in the inventory collection where the qty field exists and

Comments
  • Thanks for the response didn't looked at the drivers code. If there is no other approach I will write myself a short function
  • According to the Javadoc for getDB, the DB, DBCollection, and DBCursor classes will be deprecated in the future so it's wise to use the replacements (e.g. MongoDatabase) now. See github.com/mongodb/mongo-java-driver/blob/master/driver/src/…
  • @Paul Yep! Your statement echos everything that I mentioned (bolded and italicized and linked) in my post already. I concur 100%. :)
  • @whyceewhite why do you use "equalsIgnoreCase" instead of "equals"? collection names are case sensitive
  • @zeugor The code to which you are referring (containing equalsIngoreCase) comes directly from MongoDB's driver source code. I'm not sure why they would ignore the case since, as you pointed out, collection names are case sensitive. But take note that Mongodb deprecated this method.
  • Great idea but as you already said, it's not guaranteed to work. By the way you can write return table.count() > 0; instead as this is a valid boolean expression.
  • @Frozn Thanks for the tip! I also wanted to clarify that it is guaranteed to work as long as you have no empty collections by design.
  • This doesn't really work, another work-around would be to create a collection, if it already exists it throws an exception, and therefore you can check the error, if it contains "NamespaceExists", then you know the collection is there. Otherwise use the list and contains check above, if you don't want this mildly hacky way.
  • Hi Kiuz, seems to be something wrong with your mongoDB, maybe you had a DB with that name and removed it and it is somehow still in the meta information? If I try to do what you describe I get the correct results. Is your client connected? We are using this code snippet in production and it works just fine. I do some further testing on my side and let you know if I can somehow reproduce your description.
  • No worries, hope the code helped anyways! Btw. whoever downvoted a comment would be nice to solve the problem.