Installation
First install MongoDB on your platform based on the official documentation. On Linux you can follow this documentation. Also, MongoDB could be on the official repository, so you can install it easier.Basic CRUD Functions
Create a Java Project
First create a simple Java project (preferably with Maven).
mvn archetype:generate -DgroupId=mongoDB -DartifactId=mongoDBProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Get Mongo Java Driver
If you chose to use Maven, now you can easily use mongo-java driver in pom.xml.
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.12.1</version> </dependency>
Mongo Connection
Connect to MongoDB server:
MongoClient mongo = new MongoClient("localhost", 27017);
Mongo Database
Get database:
DB db = mongo.getDB("students_info");
Mongo Collection
Get collection / table:
DBCollection dbCollection = db.getCollection("students");
Dummy Dataset
We need to have a dummy dataset to see how CRUD functions work in MongoDB with Java.
Imagine we want to store information of students. Each studnet has a student number, full name, age, and status. Furthermore the student can join into some groups. Following class shows the strcuture of Student class:
public class Student {
private String studentNumber;
private String fullName;
private int age;
private Status status;
private List<Group> groups;
public Student(String studentNumber, String fullName, int age) {
this.studentNumber = studentNumber;
this.fullName = fullName;
this.age = age;
this.status = Status.PENDING;
this.groups = new ArrayList<Group>();
}
public Student(String studentNumber, String fullName, int age,
Status status, List<Group> groups) {
this.studentNumber = studentNumber;
this.fullName = fullName;
this.age = age;
this.status = status;
this.groups = groups;
}
public String getStudentNumber() {
return studentNumber;
}
public String getFullName() {
return fullName;
}
public int getAge() {
return age;
}
public Status getStatus() {
return status;
}
public List<Group> getGroups() {
return groups;
}
Status is an enum as shown bellow:
public enum Status {
PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D");
private String statusCode;
private Status(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusCode() {
return statusCode;
}
}
And lastly Group has the following structure:
public class Group {
private String name;
public Group(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.getName();
}
}
Now that we know about Student, following shows a simple dummy dataset:
private static List<Student> setup() {
List<Student> students = new ArrayList<Student>();
Student student1 = new Student("12345", "John", 20);
students.add(student1);
List<Group> student2Groups = new ArrayList<Group>();
student2Groups.add(new Group("Football"));
Student student2 = new Student("23456", "Michael", 21, Status.ACTIVE,
student2Groups);
students.add(student2);
List<Group> student3Groups = new ArrayList<Group>();
student3Groups.add(new Group("Football"));
student3Groups.add(new Group("Basketball"));
student3Groups.add(new Group("PingPong"));
Student student3 = new Student("34567", "Michael", 23, Status.INACTIVE,
student3Groups);
students.add(student3);
List<Group> student4Groups = new ArrayList<Group>();
Student student4 = new Student("45678", "Michael", 25, Status.DELETED,
student4Groups);
students.add(student4);
return students;
}
CREATE
Save a document into a collection named “students”.
private static void create(List<Student> students, DBCollection table) {
for (Student student : students) {
BasicDBObject document = new BasicDBObject();
document.append("studentNumber", student.getStudentNumber());
document.append("fullName", student.getFullName());
document.append("age", student.getAge());
document.append("status", student.getStatus().getStatusCode());
document.append("groups", student.getGroups().toString());
table.insert(document);
}
}
READ
Display all documents
private static void READ(DBCollection table) {
DBCursor dbCursor = table.find();
try {
while (dbCursor.hasNext()) {
System.out.println(dbCursor.next());
}
} finally {
dbCursor.close();
}
}
UPDATE
Update a document where “studentNumber=34567”.
private static void UPDATE(DBCollection table) {
BasicDBObject query = new BasicDBObject();
query.put("studentNumber", "34567");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("fullName", "Stuart");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
}
DELETE
Find document where “studentNumber=34567”, and delete it.
private static void DELETE(DBCollection table) {
BasicDBObject query = new BasicDBObject();
query.put("studentNumber", "34567");
table.remove(query);
}
Source Code
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import uk.ac.soton.ecs.mongoDB.model.Group;
import uk.ac.soton.ecs.mongoDB.model.Status;
import uk.ac.soton.ecs.mongoDB.model.Student;
public class Student {
private String studentNumber;
private String fullName;
private int age;
private Status status;
private List<Group> groups;
public Student(String studentNumber, String fullName, int age) {
this.studentNumber = studentNumber;
this.fullName = fullName;
this.age = age;
this.status = Status.PENDING;
this.groups = new ArrayList<Group>();
}
public Student(String studentNumber, String fullName, int age,
Status status, List<Group> groups) {
this.studentNumber = studentNumber;
this.fullName = fullName;
this.age = age;
this.status = status;
this.groups = groups;
}
public String getStudentNumber() {
return studentNumber;
}
public String getFullName() {
return fullName;
}
public int getAge() {
return age;
}
public Status getStatus() {
return status;
}
public List<Group> getGroups() {
return groups;
}
}
public enum Status {
PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D");
private String statusCode;
private Status(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusCode() {
return statusCode;
}
}
public class Group {
private String name;
public Group(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.getName();
}
}
public class StudentController {
public static void main(String[] args) {
try {
System.out.println("CRUD in MongoDB with Java");
// Connect to MongoDB
MongoClient mongo = new MongoClient("localhost", 27017);
// Cleanup, Get database + Get collection / table from
// 'students_info'
DBCollection table = cleanup(mongo);
// Get dummy data
System.out.println("SETUP ----------");
List<Student> students = setup();
System.out.println("DONE ----------");
// CREATE
System.out.println("CREATE ----------");
create(students, table);
System.out.println("DONE ----------");
// READ
System.out.println("READ ----------");
READ(table);
System.out.println("DONE ----------");
// UPDATE
System.out.println("UPDATE ----------");
UPDATE(table);
System.out.println("DONE ----------");
// FIND
System.out.println("FIND ----------");
FIND(table);
System.out.println("DONE ----------");
// DELETE
System.out.println("DELETE ----------");
DELETE(table);
System.out.println("DONE ----------");
// READ
System.out.println("READ ----------");
READ(table);
System.out.println("DONE ----------");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
private static void DELETE(DBCollection table) {
BasicDBObject query = new BasicDBObject();
query.put("studentNumber", "34567");
table.remove(query);
}
private static void FIND(DBCollection table) {
BasicDBObject query = new BasicDBObject();
query.put("studentNumber", "34567");
DBCursor dbCursor = table.find(query);
while (dbCursor.hasNext()) {
System.out.println(dbCursor.next());
}
}
private static void UPDATE(DBCollection table) {
BasicDBObject query = new BasicDBObject();
query.put("studentNumber", "34567");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("fullName", "Stuart");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
}
private static void READ(DBCollection table) {
DBCursor dbCursor = table.find();
try {
while (dbCursor.hasNext()) {
System.out.println(dbCursor.next());
}
} finally {
dbCursor.close();
}
}
private static void create(List<Student> students, DBCollection table) {
for (Student student : students) {
BasicDBObject document = new BasicDBObject();
document.append("studentNumber", student.getStudentNumber());
document.append("fullName", student.getFullName());
document.append("age", student.getAge());
document.append("status", student.getStatus().getStatusCode());
document.append("groups", student.getGroups().toString());
table.insert(document);
}
}
private static List<Student> setup() {
List<Student> students = new ArrayList<Student>();
Student student1 = new Student("12345", "John", 20);
students.add(student1);
List<Group> student2Groups = new ArrayList<Group>();
student2Groups.add(new Group("Football"));
Student student2 = new Student("23456", "Michael", 21, Status.ACTIVE,
student2Groups);
students.add(student2);
List<Group> student3Groups = new ArrayList<Group>();
student3Groups.add(new Group("Football"));
student3Groups.add(new Group("Basketball"));
student3Groups.add(new Group("PingPong"));
Student student3 = new Student("34567", "Michael", 23, Status.INACTIVE,
student3Groups);
students.add(student3);
List<Group> student4Groups = new ArrayList<Group>();
Student student4 = new Student("45678", "Michael", 25, Status.DELETED,
student4Groups);
students.add(student4);
return students;
}
private static DBCollection cleanup(MongoClient mongo) {
DB db = mongo.getDB("students_info");
db.dropDatabase();
db = mongo.getDB("students_info");
DBCollection dbCollection = db.getCollection("students");
return dbCollection;
}
}
No comments:
Post a Comment