[轉載]使用Java操做Mongodb

HelloWorld程序java

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

  首先,要經過Java操做Mongodb,必須先下載Mongodb的Java驅動程序,能夠在這裏下載github

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

 1 package com.mkyong.core;
 2 import java.net.UnknownHostException;
 3 import com.mongodb.BasicDBObject;
 4 import com.mongodb.DB;
 5 import com.mongodb.DBCollection;
 6 import com.mongodb.DBCursor;
 7 import com.mongodb.Mongo;
 8 import com.mongodb.MongoException;
 9 
10 /**
11 * Java + MongoDB Hello world Example
12 * 
13 */
14 public class App {
15     public static void main(String[] args) {
16         try {
17             //實例化Mongo對象,鏈接27017端口
18             Mongo mongo = new Mongo("localhost", 27017);
19                                //鏈接名爲yourdb的數據庫,假如數據庫不存在的話,mongodb會自動創建
20             DB db = mongo.getDB("yourdb");
21             // Get collection from MongoDB, database named "yourDB"
22 //從Mongodb中得到名爲yourColleection的數據集合,若是該數據集合不存在,Mongodb會爲其新創建
23             DBCollection collection = db.getCollection("yourCollection");
24     // 使用BasicDBObject對象建立一個mongodb的document,並給予賦值。
25             BasicDBObject document = new BasicDBObject();
26             document.put("id", 1001);
27             document.put("msg", "hello world mongoDB in Java");
28             //將新創建的document保存到collection中去
29             collection.insert(document);
30             // 建立要查詢的document
31             BasicDBObject searchQuery = new BasicDBObject();
32             searchQuery.put("id", 1001);
33             // 使用collection的find方法查找document
34             DBCursor cursor = collection.find(searchQuery);
35             //循環輸出結果
36             while (cursor.hasNext()) {
37             System.out.println(cursor.next());
38             }
39             System.out.println("Done"); 
40         } catch (UnknownHostException e) {
41             e.printStackTrace();
42         } catch (MongoException e) {
43             e.printStackTrace();
44         }
45     }
46 }
View Code

  最後,輸出的結果爲:數據庫

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

 

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

  getDB方法得到要鏈接的數據庫名,使用getCollection得到數據集合的名,而後經過新創建BasicDBObject對象去創建document,最後經過collection的insert方法,將創建的document保存到數據庫中去。而collection的find方法,則是用來在數據庫中查找document。app

  從Mongodb中得到collection數據集ide

  在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中去。

 

  完整的代碼以下所示:

 1 packagecom.mkyong.core;
 2    importjava.net.UnknownHostException;
 3    importjava.util.HashMap;
 4    importjava.util.Map;
 5    importcom.mongodb.BasicDBObject;
 6    importcom.mongodb.BasicDBObjectBuilder;
 7    importcom.mongodb.DB;
 8    importcom.mongodb.DBCollection;
 9    importcom.mongodb.DBCursor;
10    importcom.mongodb.DBObject;
11    importcom.mongodb.Mongo;
12    importcom.mongodb.MongoException;
13    importcom.mongodb.util.JSON;
14    /**
15    * Java MongoDB : Insert a Document
16    *
17    */
18    publicclass InsertDocumentApp {
19    publicstaticvoid main(String[] args){
20    try{
21    Mongo mongo =new Mongo("localhost", 27017);
22    DB db = mongo.getDB("yourdb");
23    // get a single collection
24    DBCollection collection = db.getCollection("dummyColl");
25    // BasicDBObject example
26    System.out.println("BasicDBObject example...");
27    BasicDBObject document =new BasicDBObject();
28    document.put("database", "mkyongDB");
29    document.put("table", "hosting");
30    BasicDBObject documentDetail =new BasicDBObject();
31    documentDetail.put("records", "99");
32    documentDetail.put("index", "vps_index1");
33    documentDetail.put("active", "true");
34    document.put("detail", documentDetail);
35    collection.insert(document);
36    DBCursor cursorDoc = collection.find();
37    while(cursorDoc.hasNext()){
38    System.out.println(cursorDoc.next());
39    }
40    collection.remove(new BasicDBObject());
41    // BasicDBObjectBuilder example
42    System.out.println("BasicDBObjectBuilder example...");
43    BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
44    .add("database", "mkyongDB")
45    .add("table", "hosting");
46    BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
47    .add("records", "99")
48    .add("index", "vps_index1")
49    .add("active", "true");
50    documentBuilder.add("detail", documentBuilderDetail.get());
51    collection.insert(documentBuilder.get());
52    DBCursor cursorDocBuilder = collection.find();
53    while(cursorDocBuilder.hasNext()){
54    System.out.println(cursorDocBuilder.next());
55    }
56    collection.remove(new BasicDBObject());
57    // Map example
58    System.out.println("Map example...");
59    Map documentMap =new HashMap();
60    documentMap.put("database", "mkyongDB");
61    documentMap.put("table", "hosting");
62    Map documentMapDetail =new HashMap();
63    documentMapDetail.put("records", "99");
64    documentMapDetail.put("index", "vps_index1");
65    documentMapDetail.put("active", "true");
66    documentMap.put("detail", documentMapDetail);
67    collection.insert(new BasicDBObject(documentMap));
68    DBCursor cursorDocMap = collection.find();
69    while(cursorDocMap.hasNext()){
70    System.out.println(cursorDocMap.next());
71    }
72    collection.remove(new BasicDBObject());
73    // JSON parse example
74    System.out.println("JSON parse example...");
75    String json ="{'database' : 'mkyongDB','table' : 'hosting',"+
76    "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
77    DBObject dbObject =(DBObject)JSON.parse(json);
78    collection.insert(dbObject);
79    DBCursor cursorDocJSON = collection.find();
80    while(cursorDocJSON.hasNext()){
81    System.out.println(cursorDocJSON.next());
82    }
83    collection.remove(new BasicDBObject());
84    }catch(UnknownHostException e){
85    e.printStackTrace();
86    }catch(MongoException e){
87    e.printStackTrace();
88    }
89    }
90    }
View Code

 

  更新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的完整例子:

 1 package com.liao;
 2    import java.net.UnknownHostException;
 3    import com.mongodb.BasicDBObject;
 4    import com.mongodb.DB;
 5    import com.mongodb.DBCollection;
 6    import com.mongodb.DBCursor;
 7    import com.mongodb.Mongo;
 8    import com.mongodb.MongoException;
 9    publicclass UpdateDocumentApp {
10    publicstaticvoid printAllDocuments(DBCollection collection){
11    DBCursor cursor = collection.find();
12    while (cursor.hasNext()) {
13    System.out.println(cursor.next());
14    }
15    }
16    publicstaticvoid removeAllDocuments(DBCollection collection){
17    collection.remove(new BasicDBObject());
18    }
19    publicstaticvoid insertDummyDocuments(DBCollection collection){
20    BasicDBObject document = new BasicDBObject();
21    document.put("hosting", "hostA");
22    document.put("type", "vps");
23    document.put("clients", 1000);
24    BasicDBObject document2 = new BasicDBObject();
25    document2.put("hosting", "hostB");
26    document2.put("type", "dedicated server");
27    document2.put("clients", 100);
28    BasicDBObject document3 = new BasicDBObject();
29    document3.put("hosting", "hostC");
30    document3.put("type", "vps");
31    document3.put("clients", 900);
32    collection.insert(document);
33    collection.insert(document2);
34    collection.insert(document3);
35    }
36    publicstaticvoid main(String[] args) {
37    try {
38    Mongo mongo = new Mongo("localhost", 27017);
39    DB db = mongo.getDB("yourdb");
40    DBCollection collection = db.getCollection("dummyColl");
41    System.out.println("Testing 1...");
42    insertDummyDocuments(collection);
43    //find hosting = hostB, and update it with new document
44    BasicDBObject newDocument = new BasicDBObject();
45    newDocument.put("hosting", "hostB");
46    newDocument.put("type", "shared host");
47    newDocument.put("clients", 111);
48    collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);
49    printAllDocuments(collection);
50    removeAllDocuments(collection);
51    System.out.println("Testing 2...");
52    insertDummyDocuments(collection);
53    BasicDBObject newDocument2 = new BasicDBObject().append("$inc",
54    new BasicDBObject().append("clients", 99));
55    collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2);
56    printAllDocuments(collection);
57    removeAllDocuments(collection);
58    System.out.println("Testing 3...");
59    insertDummyDocuments(collection);
60    BasicDBObject newDocument3 = new BasicDBObject().append("$set",
61    new BasicDBObject().append("type", "dedicated server"));
62    collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3);
63    printAllDocuments(collection);
64    removeAllDocuments(collection);
65    System.out.println("Testing 4...");
66    insertDummyDocuments(collection);
67    BasicDBObject updateQuery = new BasicDBObject().append("$set",
68    new BasicDBObject().append("clients", "888"));
69    collection.update(
70    new BasicDBObject().append("type", "vps"), updateQuery, false, true);
71    printAllDocuments(collection);
72    removeAllDocuments(collection);
73    System.out.println("Done");
74    } catch (UnknownHostException e) {
75    e.printStackTrace();
76    } catch (MongoException e) {
77    e.printStackTrace();
78    }
79    }
80    }
View Code

  查詢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的操做。

相關文章
相關標籤/搜索