Skip to content

Instantly share code, notes, and snippets.

@jyemin
Created March 8, 2023 22:34
Show Gist options
  • Save jyemin/58f711a34f5282e0bbc55a72c12f74bd to your computer and use it in GitHub Desktop.
Save jyemin/58f711a34f5282e0bbc55a72c12f74bd to your computer and use it in GitHub Desktop.
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoException;
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>";
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.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