'java.lang.NoSuchMethodError: com.mongodb.connection.DefaultClusterFactory.createCluster

I am trying to connect MongoDB with Java. This is my code

    MongoCredential mongoCredential;
    mongoCredential = MongoCredential.createCredential(<uname>, <dbname>, <password>);
    List<ServerAddress> list = Arrays.asList(new ServerAddress("localhost", 27017));

    MongoClientSettings.Builder mongoClientSettingsBuilder = MongoClientSettings.builder()
            .credential(mongoCredential)
            .applyToClusterSettings(builder -> builder.hosts(list));

    MongoClientSettings settings = mongoClientSettingsBuilder.build();      

Executing this I get the error

Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.connection.DefaultClusterFactory.createCluster(Lcom/mongodb/connection/ClusterSettings;Lcom/mongodb/connection/ServerSettings;Lcom/mongodb/connection/ConnectionPoolSettings;Lcom/mongodb/connection/StreamFactory;Lcom/mongodb/connection/StreamFactory;Ljava/util/List;Lcom/mongodb/event/CommandListener;Ljava/lang/String;Lcom/mongodb/MongoDriverInformation;Ljava/util/List;)Lcom/mongodb/connection/Cluster;

I do not know what is the reason for this. Can someone help me out with this



Solution 1:[1]

This may be a conflict and confusion caused by several mongodb-driver jar file that system detected. I just solve the similar problem--NoSuchMethodError with disabling mongodb-driver-sync and using spring-boot-starter-data-mongodb in pom.xml like the following one:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.mongodb</groupId>-->
<!--            <artifactId>mongodb-driver-sync</artifactId>-->
<!--            <version>4.2.3</version>-->
<!--        </dependency>-->

Solution 2:[2]

There are multiple mongodb-driver in your sbt file. In my case, it was

libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "4.5.1"
libraryDependencies += "org.mongodb.spark" %% "mongo-spark-connector" % "3.0.1"

Remove mongo-scala-driver dependency such that final build will look like this

libraryDependencies += "org.mongodb.spark" %% "mongo-spark-connector" % "3.0.1"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yihui Wang
Solution 2 Shantanu