Connect to MongoDB and Perform CRUD using Java

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.
Basic Concepts
It is document oriented aggregate database which stores and retrieve json documents. Mongo database stores data like key-value pairs(json structure) as a document. Each document is implicitly comes with _id key also.
Eg: Customer json document (i.e. customer record) will look like with _id key value
{
"_id" : ObjectId("5c376af48ece577520371dce"),
"firstName" : "Nagappan",
"lastName": "Subramanian",
"emailid": "nagappan08@gmail.com"
}
Set of document are available in a collection. Group of collections reside in database. It is schemaless database so any new key can be added on the fly there is no need to do any special work like changing the metadata like RDMS. If customer collection requires new field mobile number, mongo will accept the data with mobile number without any prework or setup.
Java Driver Options
MongoDB jar driver("mongo-java-driver") is legacy uber jar which is not java 9 compliant and it is also deprecated. To connect to MongoDB programatically (“mongodb-driver-sync”) would be best suitable and supported jar.
Database Installation & Setup
Download MongoDB installer based on your operating system and installer takes though the wizard with simple primitive steps. It will install as a service which mostly available in port 27017. It can also be checked through following command.
tasklist | grep mongo
Create a simple project from maven archetype template.
mvn archetype:generate -DgroupId=com.nagappans.core -DartifactId=javamongodb
Add mongo java driver as dependency in pom.xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.9.1</version>
</dependency>
Let's try to save and retrieve below Customer model.
import org.bson.types.ObjectId;
public final class Customer {
private ObjectId id;
private String firstName;
private String lastName;
private String emailId;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer{" + "id=" + id + ", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' + ", emailId='" + emailId + '\'' + '}';
}
Connect to MongoDB
Now to connect the mongo database, build the client settings with connection strings, then create mongo client which connects to the mongo database.
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
.credential(MongoCredential.createCredential("username", "auth-dbname",
"password".toCharArray())
.build();
MongoClient mongoClient = MongoClients.create(mongoClientSettings);
MongoDatabase mongoDatabase = mongoClient.getDatabase("customer-database");
MongoCollection<Customer> collection = mongoDatabase.getCollection("customer");
In old legacy jar("mongo-java-driver"), connecting to MongoDB will look as below.
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Save document to database
Create a customer object and use the collection method to persist the record.
Customer customer1 = new Customer("Rajesh", "Kannan", "rajeshkannan@gmail.com");
collection.insertOne(customer1);
If you want to insert documents in to batches then below code can be used to insert list of documents.
List<Customer> customerList = new ArrayList<Customer>();
customerList.add(new Customer("user", "one", "user-one@gmail.com"));
customerList.add(new Customer("user", "two", "user-two@gmail.com"));
customerList.add(new Customer("user", "three", "user-three@gmail.com"));
collection.insertMany(customerList);
Read data from Database
Data can be accessed from database in two ways. One way is to get the data as Json and map it your model class or register the model with Codec Registry, which will convert document to respective model .
Retrieve data as JSON
MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
MongoCollection<Document> collection = mongoDatabase.getCollection("customer");
collection.find().forEach(new Consumer<Document>() {
public void accept(Document customer) {
System.out.println(customer.toJson());
}
});
Retrieve data directly as POJO
private CodecRegistry getPojoCodecRegistry() {
return fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
}
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionSting))
.codecRegistry(getPojoCodecRegistry())
.build();
MongoClient mongoClient = MongoClients.create(mongoClientSettings);
MongoDatabase mongoDatabase = mongoClient.getDatabase("customer-database");
MongoCollection<Customer> collection = mongoDatabase.getCollection("customer", Customer.class);
collection.find().forEach(new Consumer<Customer>() {
public void accept(Customer customer) {
System.out.println(customer);
}
});
Update document
Once created document can be updated by various methods like updateOne, updateAll, findAndUpdate. Below is example of changing only one record having expected firstname will be changed.
collection.updateOne(eq("firstName", "Rajesh"), set("firstName", "Soniya"));
Delete document
Document can be deleted by having any filter parameter or delete many documents in collections.
collection.deleteOne(eq("firstName", "Soniya"));
Customized querying the document
Customer collection can be searched similar to rdms against all fields with flexibility of querying the data. Below code snippet search for customer's first name starting with r.
collection.find(Filters.regex("firstName", "r")).forEach(new Consumer<Customer>() {
public void accept(Customer customer) {
System.out.println(customer);
}
});
All the above code snippets are enclosed in a project and available in below github repo.
https://github.com/nagappan080810/connectmongodb
Reference:
http://mongodb.github.io/mongo-java-driver/3.9/driver/
http://mongodb.github.io/mongo-java-driver/3.9/bson/pojos