MongoDB: Basics with java
Now in this post we’ll see how to create database, collection, accessing documents from collection, and other CRUD operation and useful function using Java.
Prerequisites
For demo you need to add Java driver for MongoDB in your classpath.
You can download a driver from official MongoDB site.
For all demos in http://kode12.com we are using mongo-2.10.1.jar.
Connect to server
To connect with Mongo Server you can use either MongoClient or Mongo object.
Here we are using MongoClient.
Java Code:
MongoClient mongo = new MongoClient("localhost", 27017);
For basics you have to give a port on which server is listening and server ip/computer name or localhost if server is in local machine.
Creating Database
Example:
DB db = mongo.getDB("kode12");
here getDB(String dbName)
method returns object of class DB.
In this case if database “kode12” already exist than it’ll return as it is. Otherwise create an empty Database with same name and return.
> show dbs; kode12 (empty) local 0.078125GB >
Java Code:
public static void main(String[] args) { try { // connect to mongo server MongoClient mongo = new MongoClient("localhost", 27017); // create a blank database DB db = mongo.getDB("kode12"); // display statistics System.out.println(db.getStats()); } catch (UnknownHostException e) { System.out.println("Error in creating database."); e.printStackTrace(); } }
Output:
{ “serverUsed” : “localhost/127.0.0.1:27017″ , “db” : “kode12″ , “collections” : 0 , “objects” : 0 , “avgObjSize” : 0.0 , “dataSize” : 0 , “storageSize” : 0 , “numExtents” : 0 , “indexes” : 0 , “indexSize” : 0 , “fileSize” : 0 , “nsSizeMB” : 0 , “dataFileVersion” : { } , “ok” : 1.0}
Creating Collection and Insert Document
Using java you have to get DBCollection
object using object of class DB like,
DBCollection collection = db.getCollection("posts");
This will return object of class DBCollection
which is point to give collection of given database, now you can do all operation on collection.
MongoDB Command
> db.post.insert({“title”: “1. MongoDB basic setup on windows”, “author”: “vishal”});
In shell we write String to insert in { … }, but in java you have to create BasicDBObject
instance.
BasicDBObject
behave likeMap
, it store data in Key Value pair.
There are many way to create BasicDBObject
like you also can create BasicDBObject
byMap
. you can refer API for more.
Now you can use save(DBObject dbObject)
or insert(DBObject dbObject)
method to insert given object in database.The difference between save(…)
and insert(..)
is what we noticed is save has limited no of function while insert has many choice to insert data like insert(List)
, insert(DBObject[], WriteConcern)
etc… .
Note: save and insert method’s signature is DBObject
so don’t get confused, DBObject
is Interface and BasicDBObject
is Implementing Class of DBObject
.
Java Code:
public static void main(String[] args) { try { // connect to mongo server MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("kode12"); BasicDBObject dbObjectInsert = new BasicDBObject(); dbObjectInsert.append("title", "1. MongoDB basic setup on windows"); dbObjectInsert.append("author", "vishal"); DBCollection collection = db.getCollection("posts"); collection.insert(dbObjectInsert); } catch (UnknownHostException e) { e.printStackTrace(); } }
Retrieving Document
MongoDB method : find()
> db.post.find(); { “_id” : ObjectId(“534cb58b7c01221db59db194″), “title” : “1. basic setup on windows”, “author” : “vishal” } >
MySQL equivalent : SELECT * FROM post;
To retrieve using java again you have to Create object of implementing class of interface DBObject
(for ex, BasicDBObject
) or implement DBObject
interface using its all implementing class.
When you use find()
method than its return object of DBCursor
class. Which is similar like List<?> so can iterate and get all returned DBObject
. Refer below code.
// get all document in collection DBCursor cursor = collection.find(); while (cursor.hasNext()) { System.out.println(cursor.next()); }
This’ll return all document stored in collection post.
MongoDB method: findOne()
MySQL equivalent: SELECT * FROM post LIMIT 1;
In Java findOne()
return only one Document so you can direct get into DBObject
. Refer code.
// get first document in collection DBObject dbObject = collection.findOne(); System.out.println(dbObject);
Conditional Retrieving
You can use condition while retrieving documents. Suppose I want to get all post whose author is vishal.
MySQL equivalent: SELECT * FROM post where author=’vishal’;
MongoDB equivalent: db.post.find({“author”: “vishal”});
Java Code:
// get all document where author is vishal BasicDBObject findObject = new BasicDBObject(); findObject.put("author", "vishal"); DBCursor findQuery = collection.find(findObject); while (findQuery.hasNext()) { System.out.println(findQuery.next()); }
Updating Document
MySQL equivalent: UPDATE post set author=’yogeshm’ WHERE title=’ 2;
MongoDB equivalent: db.post.update({“title”: “2. MongoDB Basics with Shell”}, {$set: {“author”: “yogeshm”}})
Java Code:
public static void main(String[] args) { try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("kode12"); // get collection DBCollection collection = db.getCollection("posts"); // get post where title is "2. MongoDB basic setup on linux" BasicDBObject searchUpdate = new BasicDBObject(); searchUpdate.append("title", "2. MongoDB basic setup on linux"); // change author name from "yogesh" to "yogeshm" BasicDBObject basicDBObjectUpdate = new BasicDBObject(); basicDBObjectUpdate.append("$set", new BasicDBObject("author","yogeshm")); // update document in collection collection.update(searchUpdate, basicDBObjectUpdate); } catch (UnknownHostException e) { System.out.println("Error in creating database."); e.printStackTrace(); } }
Here we create 2 instance of BasicDBObject
, one is for searching for given condition and another is with new value which needs to be update.
And used update(DBObject, DBObject) method of collection.
Removing Document
MySQL equivalent: DELETE FROM post WHERE author=’vishal’;
MongoDB equivalent: db.post.remove({“author”: “vishal”});
Java Code:
public static void main(String[] args) { try{ MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("kode12"); //get collection DBCollection collection=db.getCollection("posts"); //remove all document where author is vishal BasicDBObject removeObject = new BasicDBObject(); removeObject.append("author","vishal"); //remove document in collection collection.remove(removeObject); //remove all document collection.remove(new BasicDBObject()); } catch (UnknownHostException e) { System.out.println("Error in creating database."); e.printStackTrace(); } }
MongoDB equivalent: db.dropDatabase();
Java Code:
public static void main(String[] args) { try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("kode12"); db.dropDatabase(); } catch (UnknownHostException e) { e.printStackTrace(); } }