Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Core MongoDB Operations with Native Java Driver

DZone 's Guide to

The Core MongoDB Operations with Native Java Driver

· Java Zone ·
Free Resource
MongoDB provides driver and client library support for many languages. Today we will see how operations made in  the previous article through the console will be performed in a Java application by using the library provided for Java language. I used the following tools and technologies in application.
  • MongoDB version 2.4.1
  • MongoDB Java Driver version 2.11.1
  • JDK version 1.7 ( also can be used smoothly with 1.6)
  • Maven 3.0.4
mongoBanner

1. MongoDB Dependencies for Project
<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>2.11.1</version>
</dependency>
2. Choosing Connection, Database and Collection with MongoDB
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); 
DB db  = mongoClient.getDB("kodcu"); 
DBCollection collection  = db.getCollection("articles");
In fact, the MongoClient example represents a connection pool for the database. The call getDB("kodcu") that is done through the client instance is similar to the " use dbName" call in the console. The method checks whether there is a database that has the same name with the parameter value. The database is selected if it exists, if not, a new one is created. A similar situation applies to the db.getCollection("articles") call. If there is not a collection with that name, it is created with the first insert. 3. The Process of Adding Records
insertRecord(new String[] {"Articles"}, 
                         "Lean Kanban Workshop", 
                         "Kanban system is an impressive approach in the field of software management for the last 10 years.", 
                         new Date(), 
                         "Altug Bilgin Altintas", 
                         new String[] {null}, 
                         collection);

public static void insertRecord(String[] category, String title, String content,
                                    Date date, String author, String[] tags, DBCollection collection){
        
        BasicDBObject document = new BasicDBObject("category", category)
                                .append("title", title)
                                .append("content", content)
                                .append("date", date)
                                .append("author", author)
                                .append("tags", tags);
        
        collection.insert(document);
        
        System.out.println("Added record: " + document);
        
}
4. The Process of Updating Records
updateRecord("title", "Lean Kanban Workshop", "tags", new String[]{"lean", "kanban", "training"}, collection);

public static void updateRecord(String findField, String findFieldNewValue, String updatedField, String[] updatedFieldNewValue, DBCollection collection){
        
        BasicDBObject query = new BasicDBObject();
	query.put(findField, findFieldNewValue);
        
	BasicDBObject findDocument = new BasicDBObject();
	findDocument.put(updatedField, updatedFieldNewValue);
 
	BasicDBObject updatedDocument = new BasicDBObject();
	updatedDocument.put("$set", findDocument);
 
	collection.update(query, updatedDocument);       
        System.out.println("Kayit guncellendi: " + updatedDocument);
    
}
5. Finding Records by Field Query, Using Regex Query
DBCursor cursor = findRecord("author", "Altug Bilgin Altintas", collection);

while (cursor.hasNext()) {
   System.out.println("Found records: " + cursor.next());
}

executeRegexQuery("content", "Backbone.*JavaScript", collection);

public static DBCursor findRecord(String field, String value, DBCollection collection){
        
        BasicDBObject query = new BasicDBObject();
	query.put(field, value);
        DBCursor dBCursor = collection.find(query);
        
        return dBCursor;
}

public static void executeRegexQuery(String field, String value, DBCollection collection){
        
        BasicDBObject query = new BasicDBObject();
        query.put(field, new BasicDBObject("$regex", "Backbone.*JavaScript").append("$options", "i"));
        DBCursor cursor = collection.find(query);
        
        System.out.println("***************** Regex Query *****************");
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
        System.out.println("***************** Regex Query *****************");
        
}
6. To List All Records
findAllRecords(collection);

public static void findAllRecords(DBCollection collection){
        
        System.out.println("***************** List all records *****************");
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
        System.out.println("***************** List all records *****************");
}
7. Deleting a Collection
dropCollection(collection);

public static void dropCollection(DBCollection collection){
        
        collection.drop();
        System.out.println("Collection is initialized");
}
Output produced by the application:
Collection is initialized Eklenen kayit: { "category" : [ "Articles"] , "title" : "Lean Kanban Workshop" , "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years." , "date" : { "$date" : "2013-04-22T09:58:45.155Z"} , "author" : "Altug Bilgin Altintas" , "tags" : [  null ] , "_id" : { "$oid" : "517509d530049e9dccd4ffb0"}} Added record: { "category" : [ "Articles"] , "title" : "Take the reins with Backbone.js! ? Free Webiner" , "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant." , "date" : { "$date" : "2013-04-22T09:58:45.194Z"} , "author" : "Kodcu.Com" , "tags" : [  null ] , "_id" : { "$oid" : "517509d530049e9dccd4ffb1"}} Added record: { "category" : [ "Java" , "Tutorial" , "Articles" , "Software"] , "title" : "Data Indexing with Java to Apache Solr" , "content" : " Hi all, I mentioned in my previous article the installation and configuration of Apache Solr, data indexing from command line to Solr and making query operations through this data." , "date" : { "$date" : "2013-04-22T09:58:45.197Z"} , "author" : "Cuneyt Yesilkaya" , "tags" : [ "java" , "data indexing with java to solr" , "solr" , "solrj"] , "_id" : { "$oid" : "517509d530049e9dccd4ffb2"}} Record is updated: { "$set" : { "tags" : [ "lean" , "kanban" , "training"]}} Found records: { "_id" : { "$oid" : "517509d530049e9dccd4ffb0"} , "author" : "Altug Bilgin Altintas" , "category" : [ "Articles"] , "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years." , "date" : { "$date" : "2013-04-22T09:58:45.155Z"} , "tags" : [ "lean" , "kanban" , "training"] , "title" : "Lean Kanban Workshop"} ***************** Regex Query ***************** { "_id" : { "$oid" : "517509d530049e9dccd4ffb1"} , "category" : [ "Articles"] , "title" : "Take the reins with Backbone.js! ? Free Webiner" , "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant." , "date" : { "$date" : "2013-04-22T09:58:45.194Z"} , "author" : "Kodcu.Com" , "tags" : [  null ]} ***************** Regex Query ***************** ***************** List all records ***************** { "_id" : { "$oid" : "517509d530049e9dccd4ffb1"} , "category" : [ "Articles"] , "title" : "Take the reins with Backbone.js! ? Free Webiner" , "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant." , "date" : { "$date" : "2013-04-22T09:58:45.194Z"} , "author" : "Kodcu.Com" , "tags" : [  null ]} { "_id" : { "$oid" : "517509d530049e9dccd4ffb2"} , "category" : [ "Java" , "Tutorial" , "Articles" , "Software"] , "title" : "Data Indexing with Java to Apache Solr" , "content" : "Hi all, I mentioned in my previous article the installation and configuration of Apache Solr, data indexing from command line to Solr and making query operations through this data." , "date" : { "$date" : "2013-04-22T09:58:45.197Z"} , "author" : "Cuneyt Yesilkaya" , "tags" : [ "java" , "data indexing with java to solr" , "solr" , "solrj"]} { "_id" : { "$oid" : "517509d530049e9dccd4ffb0"} , "author" : "Altug Bilgin Altintas" , "category" : [ "Articles"] , "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years " , "date" : { "$date" : "2013-04-22T09:58:45.155Z"} , "tags" : [ "lean" , "kanban" , "training"] , "title" : "Lean Kanban Workshop"} ***************** List all records *****************
Real content above and the application, can be accessed at  The Core MongoDB Operations with Native Java Driver 
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}