Basics of MongoDB and Java Connectivity
Posted By : Kiran Sharma | 24-Oct-2018
Before starting with MongoDB connectivity in java programs let start with a brief introduction of MongoDB.
Overview of MongoDB
MongoDB is an open source database termed as 'document database'. It facilitates us with high performance ,automatic scaling and high availability and used for high volume data storage. It is a cross platform database. The main concepts on which it works are - collection and document.
In this db, one collection(table) holds different documents. Basically document is a record(row) in MongoDb. A document consists of key-value pairs. A document is similar to json object as the value of fields may contain other documents, arrays and arrays of documents. Number of fields ,content and size of the document can be different in on collection.There is no concept of relationship between tables in this db.
{
name: "kiran",
status: "valid",
laguages-known: ["hindi","english","punjabi"]
}
Benfits of using documents:
***********************************
1. No complex joins.
2.MongoDB supports dynamic queries on document using a document based query language.
3.Any kind of conversion or mapping of application objects to databse not required.
Default mongo port is 27017.
After setting up the mongodb on system use the following commands on terminal to execute queries.
1.To connect with mongodb.
mongo
2. To display the database currently we are using.
db
3.use <databse> -> to switch the database.
Note: If we try to switch to a non existing database ,MongoDB creates the database automatically.
e.g.
use kirandb
output:
switched to db kirandb
4.To return the state of the current database.
db.stats()
output:
{
"db" : "test",
"collections" : 0,
"views" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"fsUsedSize" : 0,
"fsTotalSize" : 0,
"ok" : 1
}
5. db.collection_name.insertOne() -> inserts records.
db.kiran_tab.insertOne({name:'kiran',status:'valid',gender:'female'})
output:
{
"acknowledged" : true,
"insertedId" : ObjectId("5bd00bfc5a13eaa955964630")
}
multiple record insertion
db.kiran_tab.insertOne({name:'priya',status:'invalid',gender:'female'},{name:'anuj',status:'invalid',gender:'male'}) db.kiran_tab.insertOne({name:'kanika',status:'valid',gender:'female',languages_known:['hindi','english','punjabi']})
6.To show created collections(tables).
show collections
7. query database
e.g
db.kiran_tab.find()
output:
{ "_id" : ObjectId("5bd00bfc5a13eaa955964630"), "name" : "kiran", "status" : "valid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e185a13eaa955964631"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e465a13eaa955964632"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00ef75a13eaa955964633"), "name" : "kanika", "status" : "valid", "gender" : "female", "languages_known" : [ "hindi", "english", "punjabi" ] }
select by specific field
e.g
db.kiran_tab.find({"name":"kiran"})
output:
{ "_id" : ObjectId("5bd00bfc5a13eaa955964630"), "name" : "kiran", "status" : "valid", "gender" : "female" }
8. To come out of the mongodb terminal.
quit()
To check the port you can open mongod.conf file under etc folder using sudo vim mondod.conf command on terminal.
Default mongo port is 27017.
Java Connectivity MongoDB
First of all we require MongoDB jdbc driver.
Download from the below link
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongo-java-driver/3.8.2/
Add jar to your java program.
=>Lets have a look on simple program to connect with mongodb and count no: of documents in a collection.
import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Connectivity_Demo { public static void main(String[] args) { // Creating a Mongo client MongoClient mongo = new MongoClient("localhost", 27017); // access database MongoDatabase database = mongo.getDatabase("kirandb"); // access collection (table) MongoCollection<Document> collection = database.getCollection("kiran_tab"); System.out.println("total documents(rows) in collection " + collection.count()); mongo.close(); } }
=> create a new collection and inserting documents
import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Connectivity_Demo { public static void main(String[] args) { MongoClient mongo = new MongoClient("localhost", 27017); MongoDatabase database = mongo.getDatabase("kirandb"); MongoCollection<Document> collection = database.getCollection("mytab"); Document doc = new Document("title", "MongoDB").append("id", 1).append("description", "database").append("by", "kiran sharma"); collection.insertOne(doc); System.out.print("data inserted successfully"); mongo.close(); } }
=> Retrieving all documents from a collection
import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Connectivity_Demo { public static void main(String[] args) { MongoClient mongo = new MongoClient("localhost", 27017); MongoDatabase database = mongo.getDatabase("kirandb"); MongoCollectioncollection = database.getCollection("mytab"); FindIterable<Document> iterDoc = collection.find(); // fetching the records Iterator itr = iterDoc.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } mongo.close(); } }
Output
Document{{_id=5bd01e6fe41d053a44e2a67f, title=MongoDB, id=1, description=database, by=kiran sharma}}
=> Updating a record
previous record
{ "_id" : ObjectId("5bd00bfc5a13eaa955964630"), "name" : "kiran", "status" : "valid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e185a13eaa955964631"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e465a13eaa955964632"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00ef75a13eaa955964633"), "name" : "kanika", "status" : "valid", "gender" : "female", "languages_known" : [ "hindi", "english", "punjabi" ] }
import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; public class Connectivity_Demo { public static void main(String[] args) { MongoClient mongo = new MongoClient("localhost", 27017); MongoDatabase database = mongo.getDatabase("kirandb"); MongoCollection<Document> collection = database.getCollection("kiran_tab"); collection.updateOne(Filters.eq("name", "kiran"), Updates.set("status", "invalid")); System.out.println("Document updated"); mongo.close(); } }
After updating record
{ "_id" : ObjectId("5bd00bfc5a13eaa955964630"), "name" : "kiran", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e185a13eaa955964631"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00e465a13eaa955964632"), "name" : "priya", "status" : "invalid", "gender" : "female" }
{ "_id" : ObjectId("5bd00ef75a13eaa955964633"), "name" : "kanika", "status" : "valid", "gender" : "female", "languages_known" : [ "hindi", "english", "punjabi" ] }
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kiran Sharma
Kiran has good knowledge of java with Servlets, JSPs, Spring, and hibernate frameworks. She is very honest towards her work. Her hobby is listening to music.