http://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/connection/connect/#std-label-connect-to-mongodb
添加依赖
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.10.2</version> </dependency>Java代码
import com.mongodb.*; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import org.bson.BsonDocument; import org.bson.BsonInt64; import org.bson.Document; import org.bson.conversions.Bson; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MongoApplication { public static void main(String[] args) { String uri = "mongodb://127.0.0.1:27017"; try { MongoClient client = MongoClients.create(uri); //MongoClient client = new MongoClient(URI); //低版本可以这样,但现在是6.0 MongoDatabase database = mongoClient.getDatabase("admin"); Bson command = new BsonDocument("ping", new BsonInt64(1)); Document commandResult = database.runCommand(command); System.out.println("连接成功!"); } catch (MongoException me) { System.err.println(me); } } }如果遇到找不到这个类那个类找不到的,如:Caused by: java.lang.ClassNotFoundException: com.mongodb.internal.diagnostics.logging.Loggers
是因为mongodb-driver-sync中有几个依赖是<scope>compile</scope><optional>true</optional>
打开他的pom复制到项目中,如果是往现有项目中集成注意不要与现在的log冲突
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.6</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> <version>4.10.2</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-core</artifactId> <version>4.10.2</version> </dependency>