The Core MongoDB Operations with Native Java Driver

本文介绍如何使用MongoDB Java驱动程序进行数据库操作,包括连接数据库、添加记录、更新记录、查找记录及删除集合等核心功能。


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  
Published at DZone with permission of its author,  Hüseyin Akdoğan . 

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值