1

Hi i tried a program on mongodb which connect to mongohq but i am getting following error :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1958)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:186)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:138)
    at org.Mongoadded.main(Mongoadded.java:15)

and the code i return is :

package org;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class Mongoadded {

    public static void main(String args[]) throws UnknownHostException{

        String texturi="mongodb://mymail@gmail.com:password@emma.mongohq.com:10045/mongo";
        MongoClientURI mongoURI=new MongoClientURI(texturi);
        MongoClient mongoclient=new MongoClient(mongoURI);

        DB db=mongoclient.getDB("bhv");
        db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());

        Set<String> colls=db.getCollectionNames();
        for(String c:colls){
            System.out.println(c);
        }
    }

and mongo-java-driver i'm using is 2.10.1 . thankyou in advance

bhv
  • 5,188
  • 3
  • 35
  • 44
  • 1
    Is your authentication correct?? Are you getting `true` for `db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());` ?? – Jhanvi Nov 08 '13 at 07:05

2 Answers2

1

It seems the problem is in the username: mymail@gmail.com

The mongo client driver is actually relying on the index of @ to separate the authentication information from host name. Your code is not even reaching the db.authenticate part. It is failing at the constructor MongoClientURI(texturi)

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
0

Actually we have to create a new user for database .. and submit that values , its not account username,password . Its dbusername ,dbpassword .

i tried but it not working in mongohq..

and in the same way i tried in mongolab its worked fine.

and if anyone know to how to do in mongohq please let me know Thank you!

bhv
  • 5,188
  • 3
  • 35
  • 44
  • Hi, I meet the same problem now. Can you explain more specifically? What is **dbusername** and **dbpassword**? I mean, I can create a new user in *mLab Mongodb*, but how to use it in the code, like `getUsername()` and `getPassword()`? – JW.ZG Mar 25 '16 at 01:48