java connecting to mongodb database examples

To connect to a MongoDB database in Java, you can use the official MongoDB Java driver. Here are some examples of how to connect to a MongoDB database using the driver:

  1. Connect to a local MongoDB instance:
refer to‮figi:‬tidea.com
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

Replace "mydatabase" with the name of your database.

  1. Connect to a remote MongoDB instance:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

String uri = "mongodb://username:password@hostname:port/mydatabase";
MongoClientURI clientURI = new MongoClientURI(uri);
MongoClient mongoClient = new MongoClient(clientURI);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

Replace "username", "password", "hostname", "port", and "mydatabase" with your database credentials.

  1. Connect to a MongoDB replica set:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

String uri = "mongodb://username:password@hostname1:port1,hostname2:port2/mydatabase?replicaSet=myreplicaset";
MongoClientURI clientURI = new MongoClientURI(uri);
MongoClient mongoClient = new MongoClient(clientURI);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

Replace "username", "password", "hostname1", "port1", "hostname2", "port2", "mydatabase", and "myreplicaset" with your database credentials and replica set name.

  1. Connect to a MongoDB Atlas cluster:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

String uri = "mongodb+srv://username:[email protected]/mydatabase";
MongoClientURI clientURI = new MongoClientURI(uri);
MongoClient mongoClient = new MongoClient(clientURI);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

Replace "username", "password", "clustername", and "mydatabase" with your database credentials and cluster name.

Once you have connected to the MongoDB database, you can use the database object to perform CRUD (create, read, update, delete) operations on your collections.