Skip to content

Instantly share code, notes, and snippets.

@bluedistro
Last active April 7, 2019 13:49
Show Gist options
  • Save bluedistro/016ff67e58e855c5be3439f85f972a6b to your computer and use it in GitHub Desktop.
Save bluedistro/016ff67e58e855c5be3439f85f972a6b to your computer and use it in GitHub Desktop.
JAVA MongoDB Helper Script
/*
* A Java Script containing methods to manipulate a MongoDB
* Biney Kingsley - 07-04-2019
*
* */
package com.mongo;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.*;
public class MongoServices {
// make some variables global for general access
private MongoClient mongoClient;
private MongoCredential credential;
private MongoCollection<Document> collection;
private MongoDatabase db;
// create a MongoClient and start server on a port with a host
protected void connectServer(String host, int port) {
/*
* host: host of server
* port: port to connect to
* */
try {
mongoClient = new MongoClient(host, port);
System.out.println("Connected successfully");
}catch(Exception e) {
System.out.print("Unable to connect to server");
}
}
// return the client server after creation
protected MongoClient getClient() {
return mongoClient;
}
// create a database with user credentials
protected void createCredentials(String username, String password, String dbName) {
/*
* username: database protection credentials
* password: database protection credentials
* dbName: name of database to be created
* */
try {
credential = MongoCredential.createCredential(username, dbName, password.toCharArray());
// print status
System.out.println("Database Created successfully");
}catch(Exception e) {
System.out.println("Unable to create database");
}
}
// get the database credentials
protected MongoCredential getCredential() {
return credential;
}
// access the created database
protected void setDb(String dbName) {
/*
* dbName: access the database created and view credentials set to it
* */
try {
mongoClient = getClient();
db = mongoClient.getDatabase(dbName);
System.out.println("Database Credentials::" + credential);
}catch(Exception e) {
System.out.println("Cannot access Database with name " + dbName);
}
}
// get the created database
protected MongoDatabase getDb() {
return db;
}
// create a collection
protected void createCollection(MongoDatabase db, String collectionName) {
/*
* db: Database to hold collection
* collectionName: Name of the collection to be created
* */
try {
db.createCollection(collectionName);
System.out.println("Collection " + collectionName + " created successfully");
}catch(Exception e) {
System.out.println("Collection " + collectionName + " creation failed");
}
}
// select a collection to perform operations on
protected MongoCollection<Document> getCollection(String collectionName){
/*
* collectionName: select a collection to perform operations on it
* */
MongoDatabase db = getDb();
MongoCollection<Document> collection = db.getCollection(collectionName);
System.out.println("Collection " + collectionName + " has been selected");
return collection;
}
// insert documents into a collection
protected void insert(MongoCollection<Document> collection, Document doc) {
/*
* collection: the collection to insert documents in it
* doc: the document to insert into the database
* */
try {
collection.insertOne(doc);
System.out.println("Document has been inserted into collection");
}catch(Exception e) {
System.out.println("Could not insert document into collection");
}
}
// view all documents in a collection
protected void printDocs(MongoCollection<Document> collection) {
/*
* collection: collection to view all documents within
* */
try {
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}catch(Exception e) {
System.out.println("Failed to print documents in the collection");
}
}
// update a document
protected void updateDocument(MongoCollection<Document> collection, String key, String value, BasicDBObject newDocument) {
/*
* collection: the collection containing the document to update
* key: the unique key (ideally id field) of the document to update
* value: the value of the key (ideally the id value) of the document to update
* newDocument: data to update the current data in the document with
* */
try {
BasicDBObject searchquery = new BasicDBObject().append(key, value);
collection.updateOne(searchquery, newDocument);
System.out.println("Updated the Document successfully");
}catch(Exception e) {
System.out.println("Could not update the document with " + key + ":" + value + " pairs");
}
}
// delete a document
protected void deleteDocument(MongoCollection<Document> collection, String key, String value) {
/*
* collection: the collection containing the document to delete
* key: the unique key field of the document to delete
* value: the value of the unique key field of the document to delete
* */
try {
collection.deleteOne(Filters.eq(key, value));
System.out.print("Document with field " + key + ":" + value + " has been deleted");
}catch(Exception e) {
System.out.println("Document deletion failed");
}
}
// list collections in a db
protected void listCollection(MongoDatabase db) {
/*
* db: database in focus
* */
try {
for (String collNames: db.listCollectionNames()) {
System.out.println(collNames);
}
}catch(Exception e) {
System.out.println("Could not list collections");
}
}
// drop a collection in a db
protected void dropCollection(MongoDatabase db, String collectionName) {
/*
* db: database in focus
* collectionName: collection to drop
* */
try {
MongoCollection<Document> collection = db.getCollection(collectionName);
collection.drop();
System.out.println("Collection " + collectionName + " dropped successfully");
}catch(Exception e) {
System.out.println("Could not drop collection " + collectionName);
}
}
}
/*
* Test Driver of the MongoServices Java File
* Biney Kingsley - 07-04-2019
*
* */
package com.mongo;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoServicesTest {
public static void main(String[] args) {
MongoServices serv = new MongoServices();
serv.connectServer("localhost", 27017);
serv.createCredentials("simpleUser", "password", "anotherDb");
serv.setDb("anotherDb");
MongoDatabase database = serv.getDb();
// serv.createCollection(database, "Houses");
serv.listCollection(database);
// serv.dropCollection(database, "Houses");
MongoCollection<Document> collection = serv.getCollection("Books");
// create new Book document
Document doc = new Document("title", "Black Panther")
.append("author", "Morgan Schmidhuber")
.append("price", "GHC 30")
.append("quantity", "22");
// serv.insert(collection, doc);
serv.printDocs(collection);
// Update the document
BasicDBObject newDoc = new BasicDBObject();
newDoc.append("$set", new BasicDBObject().append("price", "GHC 900")
.append("quantity", "800"));
serv.updateDocument(collection, "author", "Morgan Schmidhuber", newDoc);
serv.printDocs(collection);
// serv.deleteDocument(collection, "author", "Biney Kingsley");
// serv.printDocs(collection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment