Showing posts with label java client. Show all posts
Showing posts with label java client. Show all posts

Wednesday, July 13, 2016

Writing java client for Mongo DB


Following are the steps
1) Create a java project in one of the IDEs. I have used Eclipse.
2) Then add following libraries to the classpath
mongodb-driver-3.2.2.jar
mongodb-driver-3.2.2-javadoc.jar
bson-3.0.2.jar
mongodb-driver-async-3.2.2.jar
mongodb-driver-core-3.2.2.jar
mongo-java-driver-3.2.2.jar
All these libraries can be downloaded from the link here. If you like you can very well use maven instead of downloading.
3) Write a simple client code
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBClient {
    public static void main(String[] args) throws Exception{
        MongoClient client = new MongoClient("localhost", 27017);
        MongoDatabase testDB = client.getDatabase("test");
     
        System.out.println("Dropping person collection in test database");
        MongoCollection<Document> collection = testDB.getCollection("person");
        collection.drop();
        System.out.println("Adding a person document in the person collection of test database");
        Document person = new Document("name", "Ashok Kumar Chava").append("age", 35).append("job", "none");
       
        collection.insertOne(person);
        person = new Document("name", "Advik Chava").append("age", 7).append("education", "PG");
        collection.insertOne(person);
        System.out.println("Now finding a persons using find");
        FindIterable<Document> persons = collection.find();
        MongoCursor<Document> personList=persons.iterator();
        while(personList.hasNext()){
            person=personList.next();
            System.out.printf("Person found, name is %s and age is %s education is %s job is %s\n", person.get("name"),
                    person.get("age"), person.get("education"), person.get("job"));
        }

        System.out.println("Closing client");
        client.close();
    }

}
4) Following will be the output of the above code
Adding a person document in the person collection of test database
Now finding a persons using find
Person found, name is Ashok Kumar Chava and age is 35 education is null job is none
Person found, name is Advik Chava and age is 7 education is PG job is null
Closing client

5) As you can see in the above code I have created a person Document and added few key values details to the Document. Also if you observe for the first person I completly ignored the eduction key value and for the second one I completely ignored the job key value. Then I am able to retrieve the values.
In the next section I will do some thing little more complicated.