اتصال به mongodb در جاوا با استفاده از فایل کانفیگ
فایل کانفیگ :
package org.project..database;
import com.mongodb.client.*;
import org.bson.Document;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class MongoDBHandler {
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCollection<Document> collection;
public MongoDBHandler(String configFilePath) {
try {
Properties properties = new Properties();
properties.load(new FileInputStream(configFilePath));
System.out.println(properties);
String host = properties.getProperty("remote_host");
int port = Integer.parseInt(properties.getProperty("remote_port"));
String dbName = properties.getProperty("remote_database");
String username = properties.getProperty("remote_user");
String password = properties.getProperty("remote_password");
String collectionName = properties.getProperty("remote_collection");
String uri = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/" + dbName;
mongoClient = MongoClients.create(uri);
database = mongoClient.getDatabase(dbName);
collection = database.getCollection(collectionName);
} catch (IOException e) {
e.printStackTrace();
}
//System.exit(0);
}
public void insertDocument(Document document) {
collection.insertOne(document);
}
public FindIterable<Document> readDocuments() {
return collection.find();
}
public long countDocuments() {
return collection.countDocuments();
}
public void updateDocument(Document query, Document update) {
collection.updateOne(query, new Document("$set", update));
}
public void deleteDocument(Document query) {
collection.deleteOne(query);
}
public MongoCollection<Document> getCollection() {
return collection;
}
}
فایل کانفیگ :
remote_host = localhost
remote_database = java
remote_user = parsa
remote_password = kav
remote_port = 27020
remote_collection = users
👍6