Mongodb快速入門之使用Java操作Mongodb


【IT168 專稿】在上一篇文章中,我們學習了Mongodb的安裝和初步使用,在本文中,將學習如何使用Java去編程實現對Mongodb的操作。

  HelloWorld程序

  學習任何程序的第一步,都是編寫HelloWorld程序,我們也不例外,看下如何通過Java編寫一個HelloWorld的程序。

  首先,要通過Java操作Mongodb,必須先下載Mongodb的Java驅動程序,可以在這里下載

  新建立一個Java工程,將下載的驅動程序放在庫文件路徑下,程序代碼如下:

package  com.mkyong.core; import  java.net.UnknownHostException; import  com.mongodb.BasicDBObject; import  com.mongodb.DB; import  com.mongodb.DBCollection; import  com.mongodb.DBCursor; import  com.mongodb.Mongo; import  com.mongodb.MongoException;
/** * Java + MongoDB Hello world Example *  */ public   class  App {      public   static   void  main(String[] args) {          try  {              // 實例化Mongo對象,連接27017端口             Mongo mongo  =   new  Mongo( " localhost " ,  27017 );                                 // 連接名為yourdb的數據庫,假如數據庫不存在的話,mongodb會自動建立             DB db  =  mongo.getDB( " yourdb " );              //  Get collection from MongoDB, database named "yourDB" // 從Mongodb中獲得名為yourColleection的數據集合,如果該數據集合不存在,Mongodb會為其新建立             DBCollection collection  =  db.getCollection( " yourCollection " );      //  使用BasicDBObject對象創建一個mongodb的document,並給予賦值。             BasicDBObject document  =   new  BasicDBObject();             document.put( " id " ,  1001 );             document.put( " msg " ,  " hello world mongoDB in Java " );              // 將新建立的document保存到collection中去             collection.insert(document);              //  創建要查詢的document             BasicDBObject searchQuery  =   new  BasicDBObject();             searchQuery.put( " id " ,  1001 );              //  使用collection的find方法查找document             DBCursor cursor  =  collection.find(searchQuery);              // 循環輸出結果              while  (cursor.hasNext()) {             System.out.println(cursor.next());             }             System.out.println( " Done " );          }  catch  (UnknownHostException e) {             e.printStackTrace();         }  catch  (MongoException e) {             e.printStackTrace();         }     } }

  最后,輸出的結果為:

{  " _id "  : {  " $oid "  :  " 4dbe5596dceace565d229dc3 " } ,                   " id "  :  1001  ,  " msg "  :  " hello world mongoDB in Java " } Done

 

  在上面的例子中,演示了使用Java對Mongodb操作的重要方法和步驟,首先通過創建Mongodb對象,傳入構造函數的參數是Mongodb的數據庫所在地址和端口,然后使用

  getDB方法獲得要連接的數據庫名,使用getCollection獲得數據集合的名,然后通過新建立BasicDBObject對象去建立document,最后通過collection的insert方法,將建立的document保存到數據庫中去。而collection的find方法,則是用來在數據庫中查找document。

  從Mongodb中獲得collection數據集

  在Mongodb中,可以通過如下方法獲得數據庫中的collection:

  DBCollection collection  =  db.getCollection( " yourCollection " );

  如果你不知道collection的名稱,可以使用db.getCollectionNames()獲得集合,然后再遍歷,如下:

  DB db  =  mongo.getDB( " yourdb " );   Set collections  =  db.getCollectionNames();    for (String collectionName : collections){   System.out.println(collectionName);   }

  完成的一個例子如下:

package  com.mkyong.core; import  java.net.UnknownHostException; import  java.util.Set; import  com.mongodb.DB; import  com.mongodb.DBCollection; import  com.mongodb.Mongo; import  com.mongodb.MongoException; /** * Java : Get collection from MongoDB *  */ public   class  GetCollectionApp { public   static   void  main(String[] args) { try  { Mongo mongo  =   new  Mongo( " localhost " ,  27017 ); DB db  =  mongo.getDB( " yourdb " ); Set < String >  collections  =  db.getCollectionNames(); for  (String collectionName : collections) { System.out.println(collectionName); } DBCollection collection  =  db.getCollection( " yourCollection " ); System.out.println(collection.toString()); System.out.println( " Done " );
} 
catch  (UnknownHostException e) { e.printStackTrace(); }  catch  (MongoException e) { e.printStackTrace(); } } }

  Mongodb中如何插入數據

  下面,講解下如何使用4種方式,將JSON數據插入到Mongodb中去。首先我們准備JSON

  格式的數據,如下:

  {    " database "  :  " mkyongDB " ,    " table "  :  " hosting " ,    " detail "  :   {   records :  99 ,   index :  " vps_index1 " ,   active :  " true "   }   }   }

 

  我們希望用不同的方式,通過JAVA代碼向Mongodb插入以上格式的JSON數據

  第一種方法,是使用BasicDBObject,方法如下代碼所示:

BasicDBObject document  =   new  BasicDBObject(); document.put( " database " ,  " mkyongDB " ); document.put( " table " ,  " hosting " ); BasicDBObject documentDetail  =   new  BasicDBObject(); documentDetail.put( " records " ,  " 99 " ); documentDetail.put( " index " ,  " vps_index1 " ); documentDetail.put( " active " ,  " true " ); document.put( " detail " , documentDetail); collection.insert(document);

  第二種方法是使用BasicDBObjectBuilder對象,如下代碼所示:

  BasicDBObjectBuilder documentBuilder  =  BasicDBObjectBuilder.start()   .add( " database " ,  " mkyongDB " )   .add( " table " ,  " hosting " );   BasicDBObjectBuilder documentBuilderDetail  =  BasicDBObjectBuilder.start()   .add( " records " ,  " 99 " )   .add( " index " ,  " vps_index1 " )   .add( " active " ,  " true " );   documentBuilder.add( " detail " , documentBuilderDetail.get());   collection.insert(documentBuilder.get());

  第三種方法是使用Map對象,代碼如下:

  Map documentMap  = new  HashMap();   documentMap.put( " database " ,  " mkyongDB " );   documentMap.put( " table " ,  " hosting " );   Map documentMapDetail  = new  HashMap();   documentMapDetail.put( " records " ,  " 99 " );   documentMapDetail.put( " index " ,  " vps_index1 " );   documentMapDetail.put( " active " ,  " true " );   documentMap.put( " detail " , documentMapDetail);   collection.insert( new  BasicDBObject(documentMap));

  第四種方法,也就是最簡單的,即直接插入JSON格式數據

  String json  = " {'database' : 'mkyongDB','table' : 'hosting', " +    " 'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}} " ;   DBObject dbObject  = (DBObject)JSON.parse(json);   collection.insert(dbObject);

  這里使用了JSON的parse方法,將解析后的JSON字符串轉變為DBObject對象后再直接插入到collection中去。

 

  完整的代碼如下所示:

  packagecom.mkyong.core;   importjava.net.UnknownHostException;   importjava.util.HashMap;   importjava.util.Map;   importcom.mongodb.BasicDBObject;   importcom.mongodb.BasicDBObjectBuilder;   importcom.mongodb.DB;   importcom.mongodb.DBCollection;   importcom.mongodb.DBCursor;   importcom.mongodb.DBObject;   importcom.mongodb.Mongo;   importcom.mongodb.MongoException;   importcom.mongodb.util.JSON;    /**   * Java MongoDB : Insert a Document   *    */   publicclass InsertDocumentApp {   publicstaticvoid main(String[] args){    try {   Mongo mongo  = new  Mongo( " localhost " ,  27017 );   DB db  =  mongo.getDB( " yourdb " );    //  get a single collection   DBCollection collection  =  db.getCollection( " dummyColl " );    //  BasicDBObject example   System.out.println( " BasicDBObject example... " );   BasicDBObject document  = new  BasicDBObject();   document.put( " database " ,  " mkyongDB " );   document.put( " table " ,  " hosting " );   BasicDBObject documentDetail  = new  BasicDBObject();   documentDetail.put( " records " ,  " 99 " );   documentDetail.put( " index " ,  " vps_index1 " );   documentDetail.put( " active " ,  " true " );   document.put( " detail " , documentDetail);   collection.insert(document);   DBCursor cursorDoc  =  collection.find();    while (cursorDoc.hasNext()){   System.out.println(cursorDoc.next());   }   collection.remove( new  BasicDBObject());    //  BasicDBObjectBuilder example   System.out.println( " BasicDBObjectBuilder example... " );   BasicDBObjectBuilder documentBuilder  =  BasicDBObjectBuilder.start()   .add( " database " ,  " mkyongDB " )   .add( " table " ,  " hosting " );   BasicDBObjectBuilder documentBuilderDetail  =  BasicDBObjectBuilder.start()   .add( " records " ,  " 99 " )   .add( " index " ,  " vps_index1 " )   .add( " active " ,  " true " );   documentBuilder.add( " detail " , documentBuilderDetail.get());   collection.insert(documentBuilder.get());   DBCursor cursorDocBuilder  =  collection.find();    while (cursorDocBuilder.hasNext()){   System.out.println(cursorDocBuilder.next());   }   collection.remove( new  BasicDBObject());    //  Map example   System.out.println( " Map example... " );   Map documentMap  = new  HashMap();   documentMap.put( " database " ,  " mkyongDB " );   documentMap.put( " table " ,  " hosting " );   Map documentMapDetail  = new  HashMap();   documentMapDetail.put( " records " ,  " 99 " );   documentMapDetail.put( " index " ,  " vps_index1 " );   documentMapDetail.put( " active " ,  " true " );   documentMap.put( " detail " , documentMapDetail);   collection.insert( new  BasicDBObject(documentMap));   DBCursor cursorDocMap  =  collection.find();    while (cursorDocMap.hasNext()){   System.out.println(cursorDocMap.next());   }   collection.remove( new  BasicDBObject());    //  JSON parse example   System.out.println( " JSON parse example... " );   String json  = " {'database' : 'mkyongDB','table' : 'hosting', " +    " 'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}} " ;   DBObject dbObject  = (DBObject)JSON.parse(json);   collection.insert(dbObject);   DBCursor cursorDocJSON  =  collection.find();    while (cursorDocJSON.hasNext()){   System.out.println(cursorDocJSON.next());   }   collection.remove( new  BasicDBObject());   } catch (UnknownHostException e){   e.printStackTrace();   } catch (MongoException e){   e.printStackTrace();   }   }   }

 

  更新Document

  假設如下的JSON格式的數據已經保存到Mongodb中去了,現在要更新相關的數據。

  { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostA "  ,  " type "  :  " vps "  ,  " clients "  :  1000 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostB "  ,  " type "  :  " dedicated server "  ,  " clients "  :  100 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostC "  ,  " type "  :  " vps "  ,  " clients "  :  900 }

   假設現在要將hosting中值為hostB的進行更新,則可以使用如下的方法:

  BasicDBObject newDocument  = new  BasicDBObject();   newDocument.put( " hosting " ,  " hostB " );   newDocument.put( " type " ,  " shared host " );   newDocument.put( " clients " ,  111 );   collection.update( new  BasicDBObject().append( " hosting " ,  " hostB " ), newDocument);

   可以看到,這里依然使用了BasicDBObject對象,並為其賦值了新的值后,然后使用collection的update方法,即可更新該對象。

  更新后的輸出如下:

  { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostA "  ,  " type "  :  " vps "  ,  " clients "  :  1000 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostB "  ,  " type "  :  " shared host "  ,  " clients "  :  111 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostC "  ,  " type "  :  " vps "  ,  " clients "  :  900 }

   另外,還可以使用mongodb中的$inc修飾符號去對某個值進行更新,比如,要將hosting值為hostB的document的clients的值得更新為199(即100+99=199),可以這樣:

  BasicDBObject newDocument  = new  BasicDBObject().append( " $inc " ,    new  BasicDBObject().append( " clients " ,  99 ));   collection.update( new  BasicDBObject().append( " hosting " ,  " hostB " ), newDocument);

   則輸出如下:

  { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostA "  ,  " type "  :  " vps "  ,  " clients "  :  1000 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostB "  ,  " type "  :  " dedicated server "  ,  " clients "  :  199 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostC "  ,  " type "  :  " vps "  ,  " clients "  :  900 }

   接下來,講解$set修飾符的使用。比如要把hosting中值為hostA的document中的

  type的值進行修改,則可以如下實現:

  BasicDBObject newDocument3  = new  BasicDBObject().append( " $set " ,    new  BasicDBObject().append( " type " ,  " dedicated server " ));   collection.update( new  BasicDBObject().append( " hosting " ,  " hostA " ), newDocument3);

   則輸出如下,把type的值從vps改為dedicated server:

  { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostB "  ,  " type "  :  " dedicated server "  ,  " clients "  :  100 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostC "  ,  " type "  :  " vps "  ,  " clients "  :  900 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostA "  ,  " clients "  :  1000  ,  " type "  :  " dedicated server " }

   要注意的是,如果不使用$set的修飾符,而只是如下代碼:

  BasicDBObject newDocument3  = new  BasicDBObject().append( " type " ,  " dedicated server " );   collection.update( new  BasicDBObject().append( " hosting " ,  " hostA " ), newDocument3);

   則會將所有的三個document的type類型都改為dedicated server了,因此要使用$set以更新特定的document的特定的值。

  如果要更新多個document中相同的值,可以使用$multi,比如,要把所有vps為type的document,將它們的clients的值更新為888,可以如下實現:

  BasicDBObject updateQuery  = new  BasicDBObject().append( " $set " ,    new  BasicDBObject().append( " clients " ,  " 888 " ));   collection.update( new  BasicDBObject().append( " type " ,  " vps " ), updateQuery,  false ,  true );
 

  輸出如下:

  { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostA "  ,  " clients "  :  " 888 "  ,  " type "  :  " vps " }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostB "  ,  " type "  :  " dedicated server "  ,  " clients "  :  100 }   { " _id "  : { " $oid "  :  " x " } ,  " hosting "  :  " hostC "  ,  " clients "  :  " 888 "  ,  " type "  :  " vps " }

 

  最后,還是給出更新document的完整例子:

   package  com.liao;    import  java.net.UnknownHostException;    import  com.mongodb.BasicDBObject;    import  com.mongodb.DB;    import  com.mongodb.DBCollection;    import  com.mongodb.DBCursor;    import  com.mongodb.Mongo;    import  com.mongodb.MongoException;   publicclass UpdateDocumentApp {   publicstaticvoid printAllDocuments(DBCollection collection){   DBCursor cursor  =  collection.find();    while  (cursor.hasNext()) {   System.out.println(cursor.next());   }   }   publicstaticvoid removeAllDocuments(DBCollection collection){   collection.remove( new  BasicDBObject());   }   publicstaticvoid insertDummyDocuments(DBCollection collection){   BasicDBObject document  =   new  BasicDBObject();   document.put( " hosting " ,  " hostA " );   document.put( " type " ,  " vps " );   document.put( " clients " ,  1000 );   BasicDBObject document2  =   new  BasicDBObject();   document2.put( " hosting " ,  " hostB " );   document2.put( " type " ,  " dedicated server " );   document2.put( " clients " ,  100 );   BasicDBObject document3  =   new  BasicDBObject();   document3.put( " hosting " ,  " hostC " );   document3.put( " type " ,  " vps " );   document3.put( " clients " ,  900 );   collection.insert(document);   collection.insert(document2);   collection.insert(document3);   }   publicstaticvoid main(String[] args) {    try  {   Mongo mongo  =   new  Mongo( " localhost " ,  27017 );   DB db  =  mongo.getDB( " yourdb " );   DBCollection collection  =  db.getCollection( " dummyColl " );   System.out.println( " Testing 1... " );   insertDummyDocuments(collection);    // find hosting = hostB, and update it with new document   BasicDBObject newDocument  =   new  BasicDBObject();   newDocument.put( " hosting " ,  " hostB " );   newDocument.put( " type " ,  " shared host " );   newDocument.put( " clients " ,  111 );   collection.update( new  BasicDBObject().append( " hosting " ,  " hostB " ), newDocument);   printAllDocuments(collection);   removeAllDocuments(collection);   System.out.println( " Testing 2... " );   insertDummyDocuments(collection);   BasicDBObject newDocument2  =   new  BasicDBObject().append( " $inc " ,    new  BasicDBObject().append( " clients " ,  99 ));   collection.update( new  BasicDBObject().append( " hosting " ,  " hostB " ), newDocument2);   printAllDocuments(collection);   removeAllDocuments(collection);   System.out.println( " Testing 3... " );   insertDummyDocuments(collection);   BasicDBObject newDocument3  =   new  BasicDBObject().append( " $set " ,    new  BasicDBObject().append( " type " ,  " dedicated server " ));   collection.update( new  BasicDBObject().append( " hosting " ,  " hostA " ), newDocument3);   printAllDocuments(collection);   removeAllDocuments(collection);   System.out.println( " Testing 4... " );   insertDummyDocuments(collection);   BasicDBObject updateQuery  =   new  BasicDBObject().append( " $set " ,    new  BasicDBObject().append( " clients " ,  " 888 " ));   collection.update(    new  BasicDBObject().append( " type " ,  " vps " ), updateQuery,  false ,  true );   printAllDocuments(collection);   removeAllDocuments(collection);   System.out.println( " Done " );   }  catch  (UnknownHostException e) {   e.printStackTrace();   }  catch  (MongoException e) {   e.printStackTrace();   }   }   }

 

  查詢Document

  下面學習如何查詢document,先用下面的代碼往數據庫中插入1-10數字:

   for ( int  i = 1 ; i  <= 10 ; i ++ ){   collection.insert( new  BasicDBObject().append( " number " , i));
  }

   接下來,看下如下的例子:

  1) 獲得數據庫中的第一個document:

  DBObject doc  =  collection.findOne();   System.out.println(dbObject);

   輸出為:

  { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80bd " } ,  " number "  :  1 }

   2)獲得document的集合

  DBCursor cursor  =  collection.find();    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   這里,使用collection.find()方法,獲得當前數據庫中所有的documents對象集合

  然后通過對DBCursor對象集合的遍歷,即可輸出當前所有documents。輸出如下:

  { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80bd " } ,  " number "  :  1 }    // ..........中間部分省略,為2到9的輸出   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c6 " } ,  " number "  :  10 }

   3) 獲取指定的document

  比如要獲得number=5的document對象內容,可以使用collection的find方法即可,如下:

  BasicDBObject query  = new  BasicDBObject();   query.put( " number " ,  5 );   DBCursor cursor  =  collection.find(query);    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   即輸出:

  { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c1 " } ,  " number "  :  5 }

   4) 使用in操作符號

  在mongodb中,也可以使用in操作符,比如要獲得number=9和number=10的document對象,可以如下操作:

  BasicDBObject query  = new  BasicDBObject();   List list  = new  ArrayList();   list.add( 9 );   list.add( 10 );   query.put( " number " ,  new  BasicDBObject( " $in " , list));   DBCursor cursor  =  collection.find(query);    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   這里使用了一個List,並將list傳入到BasicDBObject的構造函數中,並使用了in操作符號,輸出如下:

  { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c5 " } ,  " number "  :  9 }   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c6 " } ,  " number "  :  10 }

 

  5) 使用>,<等比較符號

  在mongodb中,也可以使用比如>,<等數量比較符號,比如要輸出number>5的document集合,則使用“$gt”即可,同理,小於關系則使用$lt,例子如下:

  BasicDBObject query  = new  BasicDBObject();   query.put( " number " ,  new  BasicDBObject( " $gt " ,  5 ));   DBCursor cursor  =  collection.find(query);    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   輸出如下:

  { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c2 " } ,  " number "  :  6 }   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c3 " } ,  " number "  :  7 }   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c4 " } ,  " number "  :  8 }   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c5 " } ,  " number "  :  9 }   { " _id "  : { " $oid "  :  " 4dc7f7b7bd0fb9a86c6c80c6 " } ,  " number "  :  10 }   也可以多個比較符號一起使用,比如要輸出number > 5和number < 8的document,則如下:   BasicDBObject query  = new  BasicDBObject();   query.put( " number " ,  new  BasicDBObject( " $gt " ,  5 ).append( " $lt " ,  8 ));   DBCursor cursor  =  collection.find(query);    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   同樣,如果是不等於的關系的話,可以使用$ne操作符,如下:

  BasicDBObject query5  = new  BasicDBObject();   query5.put( " number " ,  new  BasicDBObject( " $ne " ,  8 ));   DBCursor cursor6  =  collection.find(query5);    while (cursor6.hasNext()){   System.out.println(cursor6.next());   }

   以上輸出number=8之外的所有document。

  刪除document

  下面我們學習如何刪除document,依然以上面的已插入的1-10的documents集合為例說明:

  1) 刪除第一個document

  DBObject doc  =  collection.findOne();   collection.remove(doc);

   2) 刪除指定的document

  比如刪除number=2的document,如下方法:

  BasicDBObject document  = new  BasicDBObject();   document.put( " number " ,  2 );   collection.remove(document);

   要注意的是,如下的方法將只會刪除number=3的document。

  BasicDBObject document  = new  BasicDBObject();   document.put( " number " ,  2 );   document.put( " number " ,  3 );   collection.remove(document);

 

  3) 使用in 操作符號指定刪除document

  下面的例子將同時刪除number=4和number=5的document,使用的是in操作符

  BasicDBObject query2  = new  BasicDBObject();   List list  = new  ArrayList();   list.add( 4 );   list.add( 5 );   query2.put( " number " ,  new  BasicDBObject( " $in " , list));   collection.remove(query2);

  4) 使用“$gt”刪除大於某個值的document

  BasicDBObject query  = new  BasicDBObject();   query.put( " number " ,  new  BasicDBObject( " $gt " ,  9 ));   collection.remove(query);

  以上會刪除number=10的document。

  5) 刪除所有的document

  DBCursor cursor  =  collection.find();    while (cursor.hasNext()){   collection.remove(cursor.next());   }

  保存圖片到Mongodb

  下面將講解如何使用Java MongoDB GridFS API去保存圖片等二進制文件到Monodb,關於Java MongoDB GridFS API的詳細論述,請參考http://www.mongodb.org/display/DOCS/GridFS+Specification

  1)保存圖片

  代碼段如下:

  String newFileName  = " mkyong-java-image " ;   File imageFile  = newFile( " c:\\JavaWebHosting.png " );   GridFS gfsPhoto  = new  GridFS(db,  " photo " );   GridFSInputFile gfsFile  =  gfsPhoto.createFile(imageFile);   gfsFile.setFilename(newFileName);   gfsFile.save();

  這里,將c盤下的JavaWebHosting.png保存到mongodb中去,並命名為mkyong-java-image。

  2) 讀取圖片信息

  代碼段如下

  String newFileName  = " mkyong-java-image " ;   GridFS gfsPhoto  = new  GridFS(db,  " photo " );   GridFSDBFile imageForOutput  =  gfsPhoto.findOne(newFileName);   System.out.println(imageForOutput);

  將會輸出JSON格式的結果;

  {    " _id "  :   {    " $oid "  :  " 4dc9511a14a7d017fee35746 "   } ,    " chunkSize "  :  262144  ,    " length "  :  22672  ,    " md5 "  :  " 1462a6cfa27669af1d8d21c2d7dd1f8b "  ,    " filename "  :  " mkyong-java-image "  ,    " contentType "  :  null  ,    " uploadDate "  :   {    " $date "  :  " 2011-05-10T14:52:10Z "   } ,    " aliases "  :  null   }

  可以看到,輸出的是文件的屬性相關信息。

 

  3) 輸出已保存的所有圖片

  下面代碼段,輸出所有保存在photo命名空間下的圖片信息:

  GridFS gfsPhoto  = new  GridFS(db,  " photo " );   DBCursor cursor  =  gfsPhoto.getFileList();    while (cursor.hasNext()){   System.out.println(cursor.next());   }

   4) 從數據庫中讀取一張圖片並另存

  下面的代碼段,從數據庫中讀取一張圖片並另存為另外一張圖片到磁盤中

  String newFileName  = " mkyong-java-image " ;   GridFS gfsPhoto  = new  GridFS(db,  " photo " );   GridFSDBFile imageForOutput  =  gfsPhoto.findOne(newFileName);   imageForOutput.writeTo( " c:\\JavaWebHostingNew.png " );

   5) 刪除圖片

  String newFileName  = " mkyong-java-image " ;   GridFS gfsPhoto  = new  GridFS(db,  " photo " );   gfsPhoto.remove(gfsPhoto.findOne(newFileName));

   如何將JSON數據格式轉化為DBObject格式

  在mongodb中,可以使用com.mongodb.util.JSON類,將JSON格式的字符串轉變為DBObject對象。MongoDB for JAVA驅動中提供了用於向數據庫中存儲普通對象的接口DBObject,當一個文檔從MongoDB中取出時,它會自動把文檔轉換成DBObject接口類型,要將它實例化為需要的對象。比如:

  {    ' name '  :  ' mkyong ' ,    ' age '  :  30   }

   這樣的JSON格式字符串,轉換方法為:

  DBObject dbObject  = (DBObject) JSON.parse( " {'name':'mkyong', 'age':30} " );

   完整的代碼如下:

  packagecom.mkyong.core;   importjava.net.UnknownHostException;   importcom.mongodb.DB;   importcom.mongodb.DBCollection;   importcom.mongodb.DBCursor;   importcom.mongodb.DBObject;   importcom.mongodb.Mongo;   importcom.mongodb.MongoException;   importcom.mongodb.util.JSON;    /**   * Java MongoDB : Convert JSON data to DBObject   *    */   publicclass App {   publicstaticvoid main(String[] args){    try {   Mongo mongo  = new  Mongo( " localhost " ,  27017 );   DB db  =  mongo.getDB( " yourdb " );   DBCollection collection  =  db.getCollection( " dummyColl " );   DBObject dbObject  = (DBObject) JSON   .parse( " {'name':'mkyong', 'age':30} " );   collection.insert(dbObject);   DBCursor cursorDoc  =  collection.find();    while (cursorDoc.hasNext()){   System.out.println(cursorDoc.next());   }   System.out.println( " Done " );   } catch (UnknownHostException e){   e.printStackTrace();   } catch (MongoException e){   e.printStackTrace();   }   }   }

   則輸出為:

  { " _id "  : { " $oid "  :  " 4dc9ebb5237f275c2fe4959f " } ,  " name "  :  " mkyong "  ,  " age "  :  30 }
  Done

  可以看到,將JSON格式的數據類型直接轉換為mongodb中的文檔類型並輸出。

  小結:

  本文學習了如何使用Mongodb for JAVA驅動,對mongodb進行日常的數據庫操作,比如增加,刪除和修改,下一篇教程中,將指導學習Spring對mongodb的操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM