Driver package and runtime environment
Driver installation
1.Download the driver package "mongo-java-driver-3.10.1.jar" for connecting to DDS, which provides an API interface to access the DDS instance.
2.Add the following dependencies to the project's pom.xml.
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.10.1</version> </dependency>
Environment
The client needs to be configured with JDK 1.8. JDK is cross-platform and supports multiple platforms such as Windows and Linux.
Java-based connection to database
Connect using SSL certificate
3.On the Instance Management page, click the name of the instance to go to the Basic News page. After confirming that SSL is enabled, click Download Certificate in the SSL section of the Instance Information module.
4.To connect to DDS via Java, the Java link format in the code is as follows:
a.Connect to single node:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true
b.Connect to replica set:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>authSource=admin&replicaSet=replica&ssl=true
c.Connect to cluster:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true
Parameter | Description |
username | Current username. |
password | Password of the current user. |
instance_ip | If an elastic cloud server is used for connection, "instance_ip" is the IP address of the server, that is, the Intranet address of the instance on the Basic Information page. |
If the instance is accessed through a device connected to the Internet, "instance_ip" is the elastic IP bound to the instance. | |
instance_port | Port, default 8030, current port, refer to the Database Port of the instance on the Basic Information page. |
database_name | Database name, that is, the name of the database you want to connect to. |
authSource | Authenticated user database. The value is admin. |
ssl | Connection mode. When the value is true, the SSL connection mode is enabled. |
5.For Java code to connect to DDS, please refer to the following example:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class MongoDBSSLExample {
public static void main(String[] args) throws Exception {
//User name
String username = "";
//Database
String databaseName = "";
//Password
String password = "";
//Certificate path
String certPath = "";
//Connection address
String host = "";
//Port
int port = 8030;
//Create MongoCredential object
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
//Load certificate
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certPath));
//Create SSL context
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("mongodb-cert", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
//Create MongoClient instance
MongoClientOptions options = MongoClientOptions.builder()
.sslEnabled(true)
.sslInvalidHostNameAllowed(true)
.sslContext(sslContext)
.build();
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), credential, options);
}
}Certificateless Connection
6.To connect to DDS instance via Java, the Java link format in the code is as follows:
a.Connect to single node:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
b.Connect to replica set:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
c.Connect to cluster:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
7.The reference code is as follows:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
public class MongoDBExample {
public static void main(String[] args) {
//User name
String username = "";
//Database
String databaseName = "";
//Password
String password = "";
//Connection address
String host = "";
//Port
int port = 8030;
//Create MongoCredential object
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
//Create MongoClientOptions object
MongoClientOptions options = MongoClientOptions.builder()
.retryWrites(true)
.build();
//Create MongoClient instance
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), credential, options);
}
}Java-based access to database
Access DataBase
When there is an initialized MongoClient, you can access the database in the following ways:
MongoDatabase memberInfoDatabase = mongoClient.getDatabase("MemberInfo");Access collection
When obtaining a MongoDatabase instance, you can get the collection to be obtained by the following command:
MongoCollection<Document> coll = memberInfoDatabase.getCollection("gold_member");Explicitly create a collection
You can also explicitly create a collection using the createCollection() method and specify the properties of the collection at the time of creation.
memberInfoDatabase.createCollection("testCollection", new CreateCollectionOptions().sizeInBytes(200000));Insert data
Document doc0 = new Document("name", "Wansan")
.append("age", 30)
.append("sex", "male");
Document doc1 = new Document("name", "Liuya")
.append("age", 42)
.append("sex", "male");
Document doc2 = new Document("name", "Wangying")
.append("age", 22)
.append("sex", "female");
List<Document> documents = new ArrayList<>();
documents.add(doc0);
documents.add(doc1);
documents.add(doc2);
goldMemberCollection.insertMany(documents);Delete data
goldMemberCollection.deleteOne(eq("name", "Liuya"));Delete table
MongoCollection<Document> collection = memberInfoDatabase.getCollection("test");
collection.drop();Read data
MongoCursor<String> cursor = (MongoCursor<String>) goldMemberCollection.find();
while (cursor.hasNext()) {
Object result = cursor.next();
}
cursor.close();Query with filter conditions
MongoCursor<String> cursorCondition = (MongoCursor<String>)goldMemberCollection.find(
new Document("name","zhangsan")
.append("age", 5));
while (cursorCondition.hasNext()) {
Object result = cursorCondition.next();
}
cursorCondition.close();Run command
Execute buildInfo and collStats:
MongoClient mongoClientShell = (MongoClient) MongoClients.create();
MongoDatabase database = mongoClientShell.getDatabase("MemberInfo");
Document buildInfoResults = database.runCommand(new Document("buildInfo", 1));
System.out.println(buildInfoResults.toJson());
Document collStatsResults = database.runCommand(new Document("collStats", "restaurants"));
System.out.println(collStatsResults.toJson());Create Index
MongoCollection<Document> collectionTest = memberInfoDatabase.getCollection("gold_member");
collectionTest.createIndex(Indexes.ascending("age"));Example of Java-based development
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
public class MongoDBExample {
public static void main(String[] args) {
//User name
String username = "";
//Database
String databaseName = "";
//Password
String password = "";
//Connection address
String host = "";
//Port
int port = 8030;
//Create MongoCredential object
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
//Create MongoClientOptions object
MongoClientOptions options = MongoClientOptions.builder()
.retryWrites(true)
.build();
//Create MongoClient instance
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), credential, options);
//Access database
MongoDatabase memberInfoDatabase = mongoClient.getDatabase("MemberInfo");
//Access collection
MongoCollection<Document> goldMemberCollection = memberInfoDatabase.getCollection("gold_member");
//Create collection
memberInfoDatabase.createCollection("testCollection", new CreateCollectionOptions().sizeInBytes(200000));
//Insert data
Document doc0 = new Document("name", "Wansan")
.append("age", 23)
.append("sex", "male");
Document doc1 = new Document("name", "Liuya")
.append("age", 42)
.append("sex", "male");
Document doc2 = new Document("name", "Wangying")
.append("age", 22)
.append("sex", "female");
List<Document> documents = new ArrayList<>();
documents.add(doc0);
documents.add(doc1);
documents.add(doc2);
goldMemberCollection.insertMany(documents);
//Delete data
goldMemberCollection.deleteOne(eq("name", "Liuya"));
//Delete table
MongoCollection<Document> collection = memberInfoDatabase.getCollection("test");
collection.drop();
//Read data
MongoCursor<String> cursor = (MongoCursor<String>) goldMemberCollection.find();
while (cursor.hasNext()) {
Object result = cursor.next();
}
cursor.close();
//Query with filter conditions
MongoCursor<String> cursorCondition = (MongoCursor<String>)goldMemberCollection.find(
new Document("name","zhangsan")
.append("age", 5));
while (cursorCondition.hasNext()) {
Object result = cursorCondition.next();
}
cursorCondition.close();
//Run command
MongoClient mongoClientShell = (MongoClient) MongoClients.create();
MongoDatabase database = mongoClientShell.getDatabase("MemberInfo");
Document buildInfoResults = database.runCommand(new Document("buildInfo", 1));
System.out.println(buildInfoResults.toJson());
Document collStatsResults = database.runCommand(new Document("collStats", "restaurants"));
System.out.println(collStatsResults.toJson());
//Create index
MongoCollection<Document> collectionTest = memberInfoDatabase.getCollection("gold_member");
collectionTest.createIndex(Indexes.ascending("age"));
}
}