Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java's DB.getCollection() does not create collection even though the javadoc says so

Tags:

java

mongodb

The JavaDoc of DB.getCollection states:

Gets a collection with a given name. If the collection does not exist, a new collection is created.

However, it seems that the collection is actually created later. Right after the getCollection() is does not exist. When I e.g., insert a doc, then it created.

Consider this:

myCollection.getDB().getCollection("dummy").getStats()
(com.mongodb.CommandResult) { "serverUsed" : "localhost/127.0.0.1:27801" , "ok" : 0.0 , "errmsg" : "ns not found"}

In my case I was calling a mapreduce job which I passed a collection that did not yet exist. This also results in '{ "serverUsed" : "localhost/127.0.0.1:27801" , "ok" : 0.0 , "errmsg" : "ns doesn't exist"}'.

I guess the JavaDoc is incorrect. Actually the collection is lazily created later.

If so, what would be the best way to achieve the behavior to immediately create the collection?

I am using java driver version 2.11.3

like image 242
Christoph Dietze Avatar asked Feb 15 '23 20:02

Christoph Dietze


1 Answers

You are right to some extent , in java if you just use db.getCollection("COLLECTION_NAME") the collection is not created. For example:

    MongoClient mongoClient = new MongoClient("SERVER", 27017);
    DB db = mongoClient.getDB("DB_NAME");
    DBCollection coll1 = db.getCollection("COLLECTION_NAME");

Here the collection wont be created, but if you add the following lines to it, the collection will be created:

    BasicDBObject document = new BasicDBObject();
    document.put("user_id", "1");
    System.out.println(coll1.insert(document));

In your case, you can check if the collection already exists or not and then create it, if required:

    boolean collectionExists = db.collectionExists("COLLECTION_NAME");
    if (collectionExists == false) {
        db.createCollection("COLLECTION_NAME", null);
    }
like image 63
Jhanvi Avatar answered Feb 17 '23 09:02

Jhanvi