简体   繁体   中英

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?

Eclipse IDE 上的 MongoClient 实例化错误。

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);
    }
}

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.

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