This guide dmeonstrates basic CRUD operations with MongoDB using Java. Requires mongo-java-driver dependency (version 3.2.2 used here).
// Insert operation
public void insertDocument() {
try(MongoClient mongo = new MongoClient("localhost", 27017)) {
DB database = mongo.getDB("sampleDB");
DBCollection collection = database.getCollection("users");
DBObject document = new BasicDBObject();
document.put("username", "testUser");
document.put("score", 85);
collection.insert(document);
System.out.println("Document inserted successfully");
}
}
// Delete operation
public void removeDocument() {
try(MongoClient mongo = new MongoClient("localhost", 27017)) {
DB database = mongo.getDB("sampleDB");
DBCollection collection = database.getCollection("users");
DBObject query = new BasicDBObject("username", "testUser");
collection.remove(query);
System.out.println("Document removed successfully");
}
}
// Update operation
public void modifyDocument() {
try(MongoClient mongo = new MongoClient("localhost", 27017)) {
DB database = mongo.getDB("sampleDB");
DBCollection collection = database.getCollection("users");
DBObject query = new BasicDBObject("username", "testUser");
DBObject update = new BasicDBObject("$set",
new BasicDBObject("score", 90));
collection.update(query, update);
System.out.println("Document updated successfully");
}
}
// Query operation
public void findDocuments() {
try(MongoClient mongo = new MongoClient("localhost", 27017)) {
DB database = mongo.getDB("sampleDB");
DBCollection collection = database.getCollection("users");
DBObject query = new BasicDBObject("score",
new BasicDBObject("$gt", 80));
try(DBCursor cursor = collection.find(query)) {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
System.out.println("Query completed");
}
}