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. |
admin.MongoClient instance as a singleton to avoid creating new connections for each operation.<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver-sync</artifactId><version>4.11.1</version></dependency>
implementation 'org.mongodb:mongodb-driver-sync:4.11.1'
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_0String 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 documentDocument 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();}}}
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.
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
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
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.import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "users")public class User {@Idprivate String id;private String username;private Integer age;private String email;// Constructors, getters, and setters are omitted.}
import org.springframework.data.mongodb.repository.MongoRepository;public interface UserRepository extends MongoRepository<User, String> {User findByUsername(String username);}
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;@Componentpublic class MongoDBRunner implements CommandLineRunner {@Autowiredprivate UserRepository userRepository;@Overridepublic void run(String... args) {// Insert a documentUser user = new User();user.setUsername("jack");user.setAge(31);user.setEmail("jack@example.com");userRepository.save(user);// Query the documentUser found = userRepository.findByUsername("jack");System.out.println("Query result: " + found);}}
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)
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";
@ 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);
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[...]
telnet <MongoDB-instance-IP> 27017
Connected indicates that the network is reachable.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.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();
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
cmgo-xxxxxxxx_0 format and can be obtained on the instance details page in the console.com.mongodb.MongoSocketReadException: Prematurely reached end of stream
MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(uri)).applyToConnectionPoolSettings(builder -> builder.maxConnectionIdleTime(60, TimeUnit.SECONDS)) // Automatically closes idle connections after 60 seconds.build();
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.피드백