Sunteți pe pagina 1din 13

MongoDB Java CRUD Example Tutorial

Pankaj August 9, 2014 MongoDB


Earlier we looked how to install MongoDB in Unix machines and executed some commands from terminal. Today
we will look into the MongoDB Java Driver features and how to perform common operations with examples of
CRUD (Create, Read, Update, Delete) operations.
1.

MongoDB Java Driver Download

2.

Creating MongoDB Connection

3.

Connection to MongoDB Database

4.

MongoDB and Collections

5.

MongoDB Java CRUD Example

1. MongoDB Java Driver Download


If you have maven project, just add below dependency to include MongoDB java driver into your application.

1
2
3
4
5

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>

If you have a standalone project, you can download MongoDB Java Driver from this link and include it in
your project build path.
Now lets go through some basic usage of MongoDB java driver and then we will look into MongoDB Java
Example program for CRUD operations.

2. Creating MongoDB Connection


MongoClient is the interface between our java program and MongoDB server, its used to create
connection, connect to database, retrieve collection names and create/read/update/delete database,
collections, document etc.
One of the MongoDB java driver feature I like most is that its thread safe, so we can create an instance
of

MongoClient

once and reuse it. Even if multiple thread accesses it simultaneously, a connection is returned

from the internal connection pool maintained by it. For every request to the DB (find, insert etc) the Java
thread will obtain a connection from the pool, execute the operation, and release the connection. This
means the connection (socket) used may be different each time.
Below are some of the common methods to connect to a MongoDB server.

1
2
3
4
5
6
7
8
9
10

MongoClient mongoClient = new MongoClient(); //connects to default host and port i.e 127.0.0.1:27017
// or
MongoClient mongoClient = new MongoClient( "localhost" ); //connects to default port i.e 27017
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // should use this always
// or, to connect to a replica set, with auto-discovery of the primary
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));

3. Connection to MongoDB Database


Once we get the connection to MongoDB server, next step is to create the connection to the database, as
shown below. Note that if database is not present, MongoDB will create it for you.

1
2

MongoClient mongo = new MongoClient("localhost", 27017);


DB db = mongo.getDB("journaldev");

MongoClient provide a useful method to get all the database names, as shown below.

1
2
3

MongoClient mongo = new MongoClient("localhost", 27017);


List<String> dbs = mongo.getDatabaseNames();
System.out.println(dbs); // [journaldev, local, admin]

We can have user-password based authentication for databases, in that case we need to provide
authorization credentials like below.

1
2
3
4
5
6
7
8

MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toChar


MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray());
List<MongoCredential> auths = new ArrayList<MongoCredential>();
auths.add(journaldevAuth);
auths.add(testAuth);
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongo = new MongoClient(serverAddress, auths);

If you are using older versions, you need to provide authentication details after getting the DB object like
below.

1
2
3

MongoClient mongo = new MongoClient("localhost", 27017);


DB db = mongo.getDB("journaldev");
boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());

You can easily figure out flaws in the earlier approach, the authentication should be done at early stage
because we cant recover from it.

We can drop a database either by using

MongoClient dropDatabase(String db)

method or by

DBdropDatabase()

method.

Since we are dropping the database, i prefer to use MongoClient method.

4. MongoDB and Collections


Every database can have zero or multiple collections, they are like tables in relational database servers
except that you dont have specific format of data. Think of it like a generic list vs list of Strings in terms of
java programming language.
We can get all the collections names using below code.

1
2
3
4
5

MongoClient mongo = new MongoClient("localhost", 27017);


DB db = mongo.getDB("journaldev");
Set<String> collections = db.getCollectionNames();
System.out.println(collections); // [datas, names, system.indexes, users]

We can get a specific collection by providing its name, as shown below.

1
2

DB db = mongo.getDB("journaldev");
DBCollection col = db.getCollection("users");

Again if the collection doesnt exist, MongoDB will create it for you. All the data in MongoDB goes into some
collection, so at this point we are ready to perform insert/update/delete operations.
We can use

DBCollection drop()

method to drop a collection from the database.

5. MongoDB Java Example

Even though we can work on any valid JSON document in MongoDB collection, in real life we have POJO
classes that are mapped with these data. So I will create a java bean and use it for my examples.

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

package com.journaldev.mongodb.model;
public class User {
private
private
private
private

int id;
String name;
String role;
boolean isEmployee;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEmployee() {
return isEmployee;
}
public void setEmployee(boolean isEmployee) {
this.isEmployee = isEmployee;

27
28
29
30
31
32
33
34

Here is the complete example class showing all the CRUD operations one by one.

MongoDBExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package com.journaldev.mongodb.main;
import java.net.UnknownHostException;
import
import
import
import
import
import
import
import

com.journaldev.mongodb.model.User;
com.mongodb.BasicDBObjectBuilder;
com.mongodb.DB;
com.mongodb.DBCollection;
com.mongodb.DBCursor;
com.mongodb.DBObject;
com.mongodb.MongoClient;
com.mongodb.WriteResult;

public class MongoDBExample {


public static void main(String[] args) throws UnknownHostException {
User user = createUser();
DBObject doc = createDBObject(user);
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

DBCollection col = db.getCollection("users");


//create user
WriteResult result = col.insert(doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//read example
DBObject query = BasicDBObjectBuilder.start().add("_id", user.getId()).get();
DBCursor cursor = col.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
//update example
user.setName("Pankaj Kumar");
doc = createDBObject(user);
result = col.update(query, doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//delete example
result = col.remove(query);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//close resources
mongo.close();
}
private static DBObject createDBObject(User user) {

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();

docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder.get();

private static User createUser() {


User u = new User();
u.setId(2);
u.setName("Pankaj");
u.setEmployee(true);
u.setRole("CEO");
return u;
}

A sample execution results in following output.

1
2
3
4
5
6
7
8
9
10
11
12
13

null
0
false
WriteConcern
{ "_id" : 2 ,
null
1
true
WriteConcern
null
1
false
WriteConcern

{ "getlasterror" : 1} / (Continue on error? false)


"name" : "Pankaj" , "role" : "CEO" , "isEmployee" : true}

{ "getlasterror" : 1} / (Continue on error? false)

{ "getlasterror" : 1} / (Continue on error? false)

Notice that I am saving User id with _id name, this is a reserved key for the primary key of any record in the
collection. If we dont provide one, MongoDB will create one for us. Its like sequencer or auto increment
column in relational database tables.
Since I am deleting the created record, further execution wont cause any issues. But if there are duplicate
record, then we will get below errors.

1
2
3
4
5
6
7
8
9
10

Exception in thread "main" com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost:27017" , "ok" : 1


"err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.users.$_id_ dup key
"code" : 11000}
at com.mongodb.CommandResult.getWriteException(CommandResult.java:88)
at com.mongodb.CommandResult.getException(CommandResult.java:79)
at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:314)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:189)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
at com.mongodb.DBCollection.insert(DBCollection.java:93)
at com.mongodb.DBCollection.insert(DBCollection.java:78)
at com.mongodb.DBCollection.insert(DBCollection.java:120)
at com.journaldev.mongodb.main.MongoDBExample.main(MongoDBExample.java:27)

11
12
Thats all for getting your started with MongoDB Java Driver, we will look into more features in next posts

package com.devjavasource.mongodb.HelloWorldExample;
import java.util.Date;
import org.bson.Document;
import
import
import
import
import
import

com.mongodb.BasicDBObject;
com.mongodb.MongoClient;
com.mongodb.client.FindIterable;
com.mongodb.client.MongoCollection;
com.mongodb.client.MongoCursor;
com.mongodb.client.MongoDatabase;

public class App {


public static void main(String[] args) {
MongoClient mongoClient = null;
try {
// Get MongoClient Connect to MongoDB
mongoClient = new MongoClient("localhost", 27017);
// Get database
// If database doesn't exists, MongoDB will create it for you
MongoDatabase db = mongoClient.getDatabase("devjavasource");
// Get collection / table from 'devjavasource'
// If collection doesn't exists, MongoDB will create it for

you

MongoCollection<Document> collection =
db.getCollection("orders");
// Retrieve all the documents of a specified collection
retrieve(collection);
// Insert a new document into MongoDB
System.out.println("\n********MondoDB - Insert operation
******\n");

******\n");

insert(collection);
retrieve(collection);
// Update a document
System.out.println("\n********MondoDB - Update operation
update(collection);
retrieve(collection);

******\n");

System.out.println("\n********MondoDB - Delete operation


collection.deleteOne(new Document("order_id", "41704621"));
retrieve(collection);

} catch (Exception e) {
e.printStackTrace();

} finally {
mongoClient.close();
}
}
private static void update(final MongoCollection<Document>
inCollection) {
inCollection.updateOne(new Document("order_id", "41704621"),
new Document("$set", new Document("status", "Executed"))
.append("$currentDate", new
Document("lastModified",
true)));
}
private static void insert(final MongoCollection<Document>
inCollection) {
final Document document = new Document();
document.put("order_id", "41704621");
document.put("customer_name", "Stuart Adamson");
document.put("status", "Ordered");
final BasicDBObject addressDocument = new BasicDBObject();
addressDocument.put("street", "13th Street, 2 Lane");
addressDocument.put("zipcode", "30014");
addressDocument.put("building", "Avenue Park");
document.put("address", addressDocument);
final BasicDBObject itemsDocument = new BasicDBObject();
itemsDocument.put("item_id", "Item101");
itemsDocument.put("count", 21);
itemsDocument.put("date", new Date());
document.put("Items", itemsDocument);
inCollection.insertOne(document);
}
private static void retrieve(final MongoCollection<Document>
inCollection) {
final FindIterable<Document> itr = inCollection.find();
final MongoCursor<Document> mongoItr = itr.iterator();
while (mongoItr.hasNext()) {
final Document doc = mongoItr.next();
printit(doc);
}
}
private static void printit(final Document inDoc) {
System.out.println("Order Details are:");
System.out.println("====================");
inDoc.entrySet().stream().forEach(each -> {
System.out.println("Key : " + each.getKey());
System.out.println("Value : " + each.getValue());

});

S-ar putea să vă placă și