|
1 | 1 | package fundamentals;
|
2 | 2 |
|
| 3 | +import com.mongodb.*; |
3 | 4 | import org.bson.BsonDocument;
|
4 | 5 | import org.bson.BsonInt64;
|
5 | 6 | import org.bson.Document;
|
6 | 7 | import org.bson.conversions.Bson;
|
7 | 8 |
|
8 |
| -import com.mongodb.MongoClientSettings; |
9 |
| -import com.mongodb.MongoException; |
10 | 9 | import com.mongodb.client.MongoClient;
|
11 | 10 | import com.mongodb.client.MongoClients;
|
12 | 11 | import com.mongodb.client.MongoDatabase;
|
13 | 12 |
|
14 | 13 | public class MongoClientConnectionExample {
|
15 | 14 | public static void main(String[] args) {
|
16 |
| - // Replace the uri string with your MongoDB deployment's connection string |
17 |
| - String uri = "mongodb://user:[email protected]:27017/?maxPoolSize=20&w=majority"; |
| 15 | + // Replace the placeholders with your credentials and hostname |
| 16 | + String uri = "mongodb+srv://<username>:<password>@<hostname>/?retryWrites=true&w=majority"; |
18 | 17 |
|
19 |
| - try (MongoClient mongoClient = MongoClients.create(uri)) { |
| 18 | + // Construct a ServerApi instance using the ServerApi.builder() method |
| 19 | + ServerApi serverApi = ServerApi.builder() |
| 20 | + .version(ServerApiVersion.V1) |
| 21 | + .build(); |
20 | 22 |
|
21 |
| - MongoDatabase database = mongoClient.getDatabase("admin"); |
| 23 | + MongoClientSettings settings = MongoClientSettings.builder() |
| 24 | + .applyConnectionString(new ConnectionString(uri)) |
| 25 | + .serverApi(serverApi) |
| 26 | + .build(); |
22 | 27 |
|
| 28 | + // Create a new client and connect to the server |
| 29 | + try (MongoClient mongoClient = MongoClients.create(settings)) { |
| 30 | + MongoDatabase database = mongoClient.getDatabase("admin"); |
23 | 31 | try {
|
| 32 | + // Send a ping to confirm a successful connection |
24 | 33 | Bson command = new BsonDocument("ping", new BsonInt64(1));
|
25 | 34 | Document commandResult = database.runCommand(command);
|
26 |
| - System.out.println("Connected successfully to server."); |
| 35 | + System.out.println("Pinged your deployment. You successfully connected to MongoDB!"); |
27 | 36 | } catch (MongoException me) {
|
28 |
| - System.err.println("An error occurred while attempting to run a command: " + me); |
| 37 | + System.err.println(me); |
29 | 38 | }
|
30 | 39 | }
|
31 | 40 | }
|
|
0 commit comments