Created
March 8, 2023 22:33
-
-
Save jyemin/2bac632d082c832b4e300cae7f1ffa53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.mongodb.ConnectionString; | |
import com.mongodb.MongoClientSettings; | |
import com.mongodb.MongoException; | |
import com.mongodb.ServerApi; | |
import com.mongodb.ServerApiVersion; | |
import com.mongodb.client.MongoClient; | |
import com.mongodb.client.MongoClients; | |
import com.mongodb.client.MongoDatabase; | |
import org.bson.Document; | |
public class MongoClientConnectionExample { | |
public static void main(String[] args) { | |
// Replace the placeholders with your credentials and hostname | |
String connectionString = "mongodb+srv://<username>:<password>@<svrHostName>"; | |
ServerApi serverApi = ServerApi.builder() | |
.version(ServerApiVersion.V1) | |
.build(); | |
MongoClientSettings settings = MongoClientSettings.builder() | |
.applyConnectionString(new ConnectionString(connectionString)) | |
.serverApi(serverApi) | |
.build(); | |
// Create a new client and connect to the server | |
try (MongoClient mongoClient = MongoClients.create(settings)) { | |
try { | |
// Send a ping to confirm a successful connection | |
MongoDatabase database = mongoClient.getDatabase("admin"); | |
database.runCommand(new Document("ping", 1)); | |
System.out.println("Pinged your deployment. You successfully connected to MongoDB!"); | |
} catch (MongoException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment