user485498
user485498

Reputation:

MongoDB with Java, cannot get Collection

I am starting a project with MongoDB. I have my DB :

mongo=null;
    try {
        mongo = new Mongo();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MongoException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    db = mongo.getDB( "mydb" );
    System.out.print(db.getName());//just a test

And I want to show all the elements of a particular collection (in a scrollPane, but that isn't important to the question). The collection doesn't exist initially, because the database, "mydb" is empty. This is my code:

        DBCursor cur = db.getCollection("newcollection").find();//collection should be created at this point, if it doesnt exist.


        while(cur.hasNext()) { //<----exception caused here
            //do something with cursor...
        }

Even though initially the collection is empty, on further use of the application elements will be added, so I need to search through it from when the application is started to fill in my scrollPane.

This is the stacktrace:

        java.io.IOException: couldn't connect to [/127.0.0.1:27017] bc:java.net.ConnectException:     Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:222)
    at com.mongodb.DBPort.go(DBPort.java:111)
at com.mongodb.DBPort.call(DBPort.java:78)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:217)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:313)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:298)
at com.mongodb.DBCursor._check(DBCursor.java:369)
at com.mongodb.DBCursor._hasNext(DBCursor.java:492)
at com.mongodb.DBCursor.hasNext(DBCursor.java:517)
at MainFrame$MyPanel.<init>(MainFrame.java:120)//<----cur.hasNext()

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 1781

Answers (2)

Julias
Julias

Reputation: 5892

You can check before the printing if the collection exists

db.collectionExists("coll_name")

In case if not you can create it, or maybe ensure some index - It will create it automatically I'm usually doing such operation on spring startup ( for example @PostConstruct )

Upvotes: 0

Jan Zyka
Jan Zyka

Reputation: 17898

My feeling here is that you DB is not running at all. Could you try to connect to the DB from command line using "mongo" and validate it is up and running?

Upvotes: 2

Related Questions