Java Mongodb 简明教程
Java & MongoDB - Connecting Database
要连接数据库,你需要指定数据库名称;如果数据库不存在,则 MongoDB 会自动创建它。
MongoDatabase database = mongo.getDatabase("myDb");
Example
以下是连接数据库的代码片段:
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongo.getDatabase("myDb");
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
System.out.println("Credentials ::"+ credential);
}
}
现在,我们按照以下步骤编译并运行上述程序。
$javac Tester.java
$java Tester