I'm following this tutorial to learn how to connect to MongoDB in Java, however, I'm encountering a problem and despite research, I can't seem to fix it. I do exactly what the tutorial tells me to do:
MongoClientThis is my code up until now:
import com.mongodb.MongoClient;
import com.mongodb.DB;
public class MongoDemo {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("test");
}
}
Now, I think the problem is with how I added the mongo-java-driver, since I get the following error in the first line: The import com.mongodb.MongoClient cannot be resolved but I can't seem to figure out how to fix that.
I did download the correct file and added it as an external library. When I type import com.mongodb. I do get a few suggestions, however, MongoClient is not one of them. What did I do wrong?
You may be looking for something like this.
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class MongoDemo {
public static void main(String[] args) {
ServerAddress serverAddress = new ServerAddress("http://localhost", 27017);
MongoClient mongoClient = new MongoClient(serverAddress);
DB db = mongoClient.getDB("test");
}
}
When creating this, I created a maven project to manage the dependencies better and included the most recent MongoDB dependencies. Here's my POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MongoDBExample</groupId>
<artifactId>MongoDBExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.7.0</version>
</dependency>
</dependencies>
</project>
I haven't tested this, however, notice how some of the code has changed. This is because some of the code used in the demo has been deprecated. This should be close.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With