Ali
Ali

Reputation: 103

Instantiation on MongoClient produces error

Despite all the documentation that says beyond MongoDB 3.7 the MongoClient class can be instantiated, my Eclipse IDE shouts that MongClient cannot be instantiated. What could be the problem here ?

MongoClient Instantiation error on Eclipse IDE.

public class MongoDBExample 
{
    public static void main(String args[])
    {
        String result = null;
        System.out.println("Making a connection to MongoDB..!");
        MongoClient mongo_client = new MongoClient(); // ("mongodb://localhost:27017");
        result = mongo_client.getClass().toString();
        System.out.println("Result : " + result);
    }
}

Upvotes: 0

Views: 924

Answers (1)

Alexandre Juma
Alexandre Juma

Reputation: 3323

You're trying to instatiate MongoClient with the Legacy MongoDB Java Driver API way.

Since version 3.7, you should do it this way:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

public class MongoConnect {
        public static void main(String args[])
        {
            MongoClient mongo_client_constructor1 = MongoClients.create(); // ("mongodb://localhost:27017");
            MongoClient mongo_client_constructor2 = MongoClients.create("mongodb://hostOne:27017,hostTwo:27018");

        }
}

The differences between the MongoDB Java Driver Legacy API and New API can be found clearly explained here

Also see the version 3.9 Javadoc for MongoClients, a factory for MongoClient instances.

Upvotes: 3

Related Questions