tencent cloud

TencentDB for MongoDB

Java SDK

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-06-11 11:36:10

Scenarios

Java is one of the mainstream languages for enterprise application development. The official MongoDB Java Driver provides both synchronous and asynchronous APIs and integrates seamlessly with Spring Data MongoDB. This document walks you through a complete example of connecting to TencentDB for MongoDB using the Java driver, covering both native driver usage and Spring Boot integration.

Prerequisites

You have created a TencentDB for MongoDB instance, and the instance status is Running.
You have prepared a CVM instance that resides in the same VPC as the MongoDB instance, and you have installed JDK version 8 or later.
Maven or Gradle build tools have been configured in the development environment.

Driver Version

Note:
The legacy mongo-java-driver (3.x) is no longer maintained. Please migrate to version 4.x.
Drive
Recommended Version
Compatible MongoDB Version
Description
mongodb-driver-sync
4.9 or above
4.0 - 8.0
The official synchronous driver is suitable for traditional blocking programming.
mongodb-driver-reactivestreams
4.9 or above
4.0 - 8.0
The official reactive driver is suitable for asynchronous non-blocking scenarios.

Must-Knows

Authentication Database Configuration: Whether you use the native driver or Spring Data MongoDB, you must specify the authentication database as admin.
Connection Pool Management: In production environments, reuse the MongoClient instance as a singleton to avoid creating new connections for each operation.
Resource Release: Always close the MongoClient after use. We recommend using the try-with-resources statement for automatic resource management.
Exception Handling: In production code, catch MongoException and its subclasses, and implement appropriate retry or alerting logic.

Adding Dependencies

Maven(pom.xml):
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
Gradle(build.gradle):
implementation 'org.mongodb:mongodb-driver-sync:4.11.1'

Method 1: Connecting with the Native Java Driver

The following example demonstrates how to connect to TencentDB for MongoDB using the MongoDB Java Driver and perform document insertion and query operations.
package com.example.mongodb;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.concurrent.TimeUnit;

public class MongoDBDemo {

public static void main(String[] args) {
// Connection URI (Replace with your actual connection information)
// Replica set connection string format:
// mongodb://mongouser:<password>@<IP1>:27017,<IP2>:27017,<IP3>:27017/admin?replicaSet=cmgo-xxxxxxxx_0
String uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin";

// Configure connection parameters (including connection pool settings)
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.applyToConnectionPoolSettings(builder -> builder
.maxSize(50) // Maximum size of the connection pool
.minSize(5) // Minimum size of the connection pool
.maxWaitTime(5, TimeUnit.SECONDS) // Timeout for waiting for an available connection
.maxConnectionIdleTime(60, TimeUnit.SECONDS)) // Idle connection timeout
.applyToSocketSettings(builder -> builder
.connectTimeout(10, TimeUnit.SECONDS) // Connection timeout
.readTimeout(30, TimeUnit.SECONDS)) // Read timeout
.retryWrites(true) // Enable retryable writes
.retryReads(true) // Enable retryable reads
.build();

// Create a client connection (automatically closed using try-with-resources)
try (MongoClient mongoClient = MongoClients.create(settings)) {
// Select a database.
MongoDatabase database = mongoClient.getDatabase("mydb");

// Obtain a collection.
MongoCollection<Document> collection = database.getCollection("users");

// Insert a document.
Document doc = new Document("username", "jack")
.append("age", 31)
.append("email", "jack@example.com");
collection.insertOne(doc);
System.out.println("Inserted document: " + doc.toJson());

// Query the document
Document result = collection.find(Filters.eq("username", "jack")).first();
if (result != null) {
System.out.println("Query result: " + result.toJson());
}

// Update the document.
collection.updateOne(
Filters.eq("username", "jack"),
new Document("$set", new Document("age", 32))
);
System.out.println("Update completed.");

// Delete the document.
collection.deleteOne(Filters.eq("username", "jack"));
System.out.println("Deletion completed.");

} catch (Exception e) {
System.err.println("Database operation failed: " + e.getMessage());
e.printStackTrace();
}
}
}
Sample Output:
Insert a document: {"username": "jack", "age": 31, "email": "jack@example.com", "_id": {"$oid": "6789abcdef1234567890abcd"}}
Query result: {"_id": {"$oid": "6789abcdef1234567890abcd"}, "username": "jack", "age": 31, "email": "jack@example.com"}
The update is completed.
Deletion completed.

Method 2: Spring Boot Integration

Spring Boot provides declarative database operation support through Spring Data MongoDB, simplifying the development process.

Adding Dependencies

Maven(pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Configuring Connection Information

application.yml:
spring:
data:
mongodb:
uri: mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin
# Replica set connection string:
# uri: mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017,IP3:27017/mydb?authSource=admin&replicaSet=cmgo-xxxxxxxx_0
Note:
authSource=admin is a required configuration item. TencentDB for MongoDB uniformly uses the admin database as the authentication database. In the URI, /mydb is the business database name, which is a different concept from the authentication database admin.

Defining Entity Classes

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {
@Id
private String id;
private String username;
private Integer age;
private String email;

// Constructors, getters, and setters are omitted.
}

Defining a Repository

import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserRepository extends MongoRepository<User, String> {
User findByUsername(String username);
}

Example

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MongoDBRunner implements CommandLineRunner {

@Autowired
private UserRepository userRepository;

@Override
public void run(String... args) {
// Insert a document
User user = new User();
user.setUsername("jack");
user.setAge(31);
user.setEmail("jack@example.com");
userRepository.save(user);

// Query the document
User found = userRepository.findByUsername("jack");
System.out.println("Query result: " + found);
}
}

FAQs

MongoSecurityException: Authentication failed During Connection

Exception stack sample:
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='mongouser', source='admin', ...}
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed)
Troubleshoot by following these steps:
1. Confirm that the authentication database is specified in the URI.admin: All users of TencentDB for MongoDB uniformly use admin as the authentication database. Confirm that the URI format is correct:
// Correct: The URI path points to admin.
String uri1 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin";
// Correct: Specify the authentication database via the authSource parameter when connecting to the business database.
String uri2 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin";

// Error: When connecting to the business database without specifying authSource, the driver defaults to authenticating with the mydb database, causing authentication to fail.
String uri3 = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb";
2. Confirm that special characters in the password have been URL-encoded: If the password contains special characters such as @ or :, encode them in the URI:
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

String password = URLEncoder.encode("pass@123", StandardCharsets.UTF_8);
String uri = String.format("mongodb://mongouser:%s@10.66.187.127:27017/admin", password);
3. Confirm that the username and password are correct: Log in to the MongoDB console and verify the username information on the instance management page. If you have forgotten the password, you can reset it in the console.

MongoTimeoutException: Timed out while waiting to connect

Exception Information Example:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[...]
Troubleshoot by following these steps:
1. Confirm network connectivity: Run the following command on the CVM to verify whether the network to the MongoDB instance is reachable:
telnet <MongoDB-instance-IP> 27017
An output of Connected indicates that the network is reachable.
An output of Connection timed out indicates that the network is unreachable. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.
2. Check the connection timeout configuration: Ensure that the connectTimeoutMS configuration value is reasonable. In a private network environment, 10 seconds (10000 ms) is sufficient:
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.applyToSocketSettings(builder -> builder
.connectTimeout(10, TimeUnit.SECONDS))
.build();
3. Step 3: Confirm that the replica set name is correct: If you are using a replica set connection string, confirm that the replicaSet parameter value matches the replica set name displayed on the instance details page in the console:
mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017/admin?replicaSet=cmgo-xxxxxxxx_0
Note:
The replica set name is typically in the cmgo-xxxxxxxx_0 format and can be obtained on the instance details page in the console.

MongoSocketReadException: Prematurely reached end of stream after the system has been running for a period

Exception Information Example:
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
This exception is usually caused by idle connections being actively closed by the server. Check the idle timeout configuration of the connection pool:
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.applyToConnectionPoolSettings(builder -> builder
.maxConnectionIdleTime(60, TimeUnit.SECONDS)) // Automatically closes idle connections after 60 seconds
.build();
Note:
Set maxConnectionIdleTime to 60 seconds. This prevents the client from reusing idle connections that have already been closed by the server. In addition, enable retryWrites(true) and retryReads(true) so that the driver automatically retries operations that fail due to connection closure.

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백