Documente Academic
Documente Profesional
Documente Cultură
2.
3.
4.
5.
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.
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)));
1
2
MongoClient provide a useful method to get all the database names, as shown below.
1
2
3
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
If you are using older versions, you need to provide authentication details after getting the DB object like
below.
1
2
3
You can easily figure out flaws in the earlier approach, the authentication should be done at early stage
because we cant recover from it.
method or by
DBdropDatabase()
method.
1
2
3
4
5
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()
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;
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;
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
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
docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder.get();
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
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
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;
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");
} 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());
});