简体   繁体   中英

Runtime Exception In Mongo Db Java Query

I am new to java. I am doing a search in window-builder using java-mongodb.

When I execute the below code i get Runtime exception error.

try{   
    // To connect to mongodb server
     MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
      // Now connect to your databases
     DB db = mongoClient.getDB( "Ticket" );
                 System.out.println("Connect to database successfully");
                 DBCollection coll = db.getCollection("OnlineT");
                 System.out.println("Collection created successfully");
                 F_stn = (String)fm.getSelectedItem();
                 T_stn = (String)to.getSelectedItem();
                 BasicDBObject doc = new BasicDBObject("From",F_stn);
                 BasicDBObject doc1 = new BasicDBObject("To",T_stn);
                    DBCursor ser  = coll.find(doc);
                    DBCursor ser2  = coll.find(doc1);


                    while(ser.hasNext())
                    {
                        String data=ser.next().get("To").toString();
                        System.out.println(data);
                        if(data.equals(T_stn))
                        {
                            System.out.println("i m in");

                            String dis=ser.next().toString();

                            System.out.println(dis);
                            break;
                        }
                        else
                            System.out.println("No data found");


                    }
            }

It is working fine but when it enters the if loop it did not print the DBobject.

Please suggest me some way to do this. Thanks in advance..

In the "if" loop, you have: String dis=ser.next().toString();

This makes your cursor move to the next postion and it didn't check hasNext(). I think that is the problem

Instead, you may do something like:

while(ser.hasNext()){
    DBObject dbObject = ser.next();
    String data=dbObject.get("To").toString();
    System.out.println(data);
    if(data.equals(T_stn))
                    {
                        System.out.println("i m in");
                        System.out.println(dbObject);
                        break;
                    }
                    else
                        System.out.println("No data found");

In addition, you don't need toString() for printing, println() will call automatically toString() method of the object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM