如何使用JDBC程序连接到MongoDB数据库?

MongoDB是一个跨平台的,面向文档的数据库,可提供高性能,高可用性和易扩展性。MongoDB致力于收集和文档的概念。

在开始连接MongoDB之前,需要确保您具有MongoDB JDBC驱动程序。如果不是,请从路径下载mongo.jar下载jar,然后将其添加到您的类路径中。

示例

以下JDBC程序建立与MongoDB数据库的连接并在其中创建一个集合。

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
   public static void main( String args[] ) {
      //创建一个Mongo客户端
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //创建凭证
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
      System.out.println("Connected to the database successfully");
      //访问数据库
      MongoDatabase database = mongo.getDatabase("myDb");
      //创建一个集合
      database.createCollection("sampleCollection");
      System.out.println("Collection created successfully");
   }
}

输出结果

Connected to the database successfully
Collection created successfully