MongoDB notes (12) Access MongoDB through java

Experimental environment: MongoDB 3.4.4 eclipse

1. Download the driver package and import it into the environment

Download link : Central Repository: org/mongodb (

I downloaded mongodb-driver-3.4.2.jar, mongodb-driver-core-3.4.2.jar, bson-3.4.2.jar

Note: The three installation packages need to be used together, and the versions must be consistent , otherwise an error will be reported when running

Import into the environment method:

Right click on the project (normal java project) -> Build Path -> Configure Build Path

java Build Path -> Libraries ->Add External JARs... ->Select the three jar packages you just downloaded ->apply

2. Test whether the connection is successful

import com.mongodb.MongoClient;import com.mongodb.client.MongoDatabase; public class example {	public static void main(String[] args) {		try {			MongoClient mongoClient = new MongoClient("localhost",27017);			MongoDatabase mDatabase = mongoClient.getDatabase("goodsdb");			System.out.println("Connect to database successfully");			System.out.println("MongoDataBase inof is:"+ mDatabase.getName());					}catch (Exception e) {			System.out.println(e.getClass().getName() + ":" + e.getMessage());		}	} }

Note: start mongo.exe before running

Successful result

[problem solved]

Problem Description:

The package com.mongodb is accessible from more than one module: mongodb.driver, mongodb.driver.core

Run it, the error result is:

The reason for the error: the imported jar package should not be in ModulePath, but in Classpath

Import correctly: