2012年5月29日 星期二

[ MongoDB 教學 ] Java Driver Usage Tutorial


來源自 這裡
Introduction :
這篇 Post 主要在介紹如何使用 MongoDB Java Driver, 更多的 API 使用可以參考 online API Documentation for Java Driver.

A Quick Tour :
使用 Java driver 來操作 MongoDB 跟其他 DB driver 使用上沒什麼差別, 首先需要去下載 mongo.jar 並加到你專案的 classpath. 並參考下面範例代碼來進行 MongoDB 的使用教學.

- Making A Connection
要連上 MongoDB, 你需要一個 database 的名稱, 而該 database 的名稱不需要事先存在, 如果它不存在, MongoDB 會自動建立 ; 接著你需要指定 MongoDB server 的位置 address (也就是你裝 MongoDB 的位置) 與連接 port. 下面的範例代碼示範三種方法連接 local machine 的 database "mydb" :
  1. import com.mongodb.Mongo;  
  2. import com.mongodb.DB;  
  3. import com.mongodb.DBCollection;  
  4. import com.mongodb.BasicDBObject;  
  5. import com.mongodb.DBObject;  
  6. import com.mongodb.DBCursor;  
  7.   
  8. Mongo m = new Mongo();  
  9. // or  
  10. Mongo m = new Mongo( "localhost" );  
  11. // or  
  12. Mongo m = new Mongo( "localhost" , 27017 );  
  13.   
  14. DB db = m.getDB( "mydb" );  
上面代碼會建立一個 db 物件, 代表著與 MongoDB 的連線 database "mydb". 透過它你可以對 database 進行進一步的操作. 另外要注意的是該 db 物件已經幫你考慮 connections pool 的機制, 所以你不需要自己實作 multiple threads 來建立類似的 connections pool.

另外 Mongo class 設計上是 thread saft, 所以你可以在不同的線程間使用. 如果因為某些原因, 你需要建立多個 mongo DB 物件, 注意下面事項 :
* all resource usage limits (max connections, etc) apply per mongo instance
* to dispose of an instance, make sure you call mongo.close() to clean up resources


- Authentication (Optional)
如果你使用的 MongoDB 有設定需要 username/password 的 authentication, 則可以如下進行使用前的驗證 :
  1. boolean auth = db.authenticate(myUserName, myPassword);  
如果返回的 auth 是 True 即成功完成驗證 ; 如果是 False, 則需要檢查 MongoDB 的 log (/var/log/mongo/mongod.log) 做進一步除錯.

- Getting A List Of Collections
每個 database 都有一個或以上的 collections (也可能沒有半個.), 你可以透過下面代碼檢視某個 database 下所有的 collections :
  1. Set colls = db.getCollectionNames();  
  2.   
  3. for (String s : colls) {  
  4.     System.out.println(s);  
  5. }  
- Getting A Collection
如果你要取出某個 collection, 則可以透過方法 getCollection(String collectionName) 取得, 代碼如下 :
  1. DBCollection coll = db.getCollection("testCollection")  
(Once you have this collection object, you can now do things like insert data, query for data, etc)

- Inserting a Document
一旦你取得 collection 物件, 你就可以對它進行操作如 insert documents etc. 假設我們有一個 document 以 JSON 定義格式如下 :
  1. {  
  2.    "name" : "MongoDB",  
  3.    "type" : "database",  
  4.    "count" : 1,  
  5.    "info" : {  
  6.                x : 203,  
  7.                y : 102  
  8.              }  
  9. }  
可以發現上面的 document 有一個 "inner" embedded document 在裡面. 接著我們可以使用類別 BasicDBObject 來建立上面定義的 document , 並且將它插入到我們剛剛取出的 collection :
  1. BasicDBObject doc = new BasicDBObject();  
  2.   
  3. doc.put("name""MongoDB");  
  4. doc.put("type""database");  
  5. doc.put("count"1);  
  6.   
  7. BasicDBObject info = new BasicDBObject();  
  8.   
  9. info.put("x"203);  
  10. info.put("y"102);  
  11.   
  12. doc.put("info", info);  
  13.   
  14. coll.insert(doc);  
- Finding the First Document In A Collection using findOne()
為了驗證剛剛我們的 document 已經成功插入 collection, 接著我們要透過方法 findOne() 取剛 collection 中的第一個 document. 這個方法返回一個 single document (rather than theDBCursor that the find() operation returns), 範例代碼如下 :
  1. DBObject myDoc = coll.findOne();  
  2. System.out.println(myDoc);  
執行後你可以在 Console 看到 :
{ "_id" : { "$oid" : "4fc57c87ee010ec3ff8702f4"} , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}

上面的 _id 是 MongoDB 自動加到你的 document, 主要是當作 identify key 使用. (Remember, MongoDB reserves element names that start with "_"/"$" for internal use.)

- Adding Multiple Documents
為了等下 DB Query 的教學, 我們先來建立一些測試用的 simple documents 到 collection 中. 這些 simple document 格式如下 :
  1. {  
  2.    "i" : value  
  3. }  
接著我們可以透過一個 loop 插入 multiple documents 到 collection :
  1. for (int i=0; i < 100; i++) {  
  2.     coll.insert(new BasicDBObject().append("i", i));  
  3. }  
這邊可以發現這邊的 document 的 scheme 與第一個 document 不同, 而這也是為什麼 MongoDB 會是 "schema-free" 的原因!

- Counting Documents in A Collection
執行完畢上面的 loop 後, 我們預期會有 101 個 documents 在 collection 中 (the 100 we did in the loop, plus the first one). 我們可以透過 getCount() 法來驗證我們的猜測 :
  1. System.out.println(coll.getCount());  
- Using a Cursor to Get All the Documents
為了要取出 collection 中所有的 documents, 這邊我們會使用方法 find(), 它會返回 DBCursor 物件, 透過這個物件我們可以走訪 collection 所有的 document :
  1. DBCollection coll  = retvCollection("mydb");  
  2. System.out.printf("\t[Info] Collection='%s' total have %d docs :\n""mydb", coll.getCount());  
  3. DBCursor cur = coll.find();  
  4.   
  5. while(cur.hasNext()) {  
  6.     System.out.println(cur.next());  
  7. }  
在 Console 輸出如下 :


- Getting A Single Document with A Query
document 存在 collection, 但是有時我只想出取某些 document subset 而不是整個 document set. 這時就可以透過建立 query 並傳入 find(DBObject ref) 來取回滿足 query 的 document subset. 假設我們要取出 "i" = 71 的 document, 則可以參考下面代碼 :
  1. DBCollection coll  = retvCollection("mydb");  
  2. BasicDBObject query = new BasicDBObject();  
  3. query.put("i"71);  
  4.           
  5. System.out.printf("\t[Info] Query=%s :\n", query);  
  6.   
  7. DBCursor cur = coll.find(query);  
  8. while(cur.hasNext()) {  
  9.     System.out.println(cur.next());  
  10. }  
其實在 MongoDB 透過 $ operator, 你可以寫出更強大的 query :
  1. db.things.find({j: {$ne: 3}, k: {$gt: 10} });  
而上面的寫法等於下面的代碼 :
  1. BasicDBObject query = new BasicDBObject();  
  2.   
  3. query.put("j"new BasicDBObject("$ne"3));  
  4. query.put("k"new BasicDBObject("$gt"10));  
  5.   
  6. cur = coll.find(query);  
  7. while(cur.hasNext()) {  
  8.     System.out.println(cur.next());  
  9. }  
- Getting A Set of Documents With a Query
上面的 query 只取回一個 document, 這邊我們要用更複雜的 query 並取回不只一個 document. 考慮 query = "i" > 50 :
  1. DBCollection coll  = retvCollection("mydb");  
  2. BasicDBObject query = new BasicDBObject();  
  3. query.put("i"new BasicDBObject("$gt"50));  // e.g. find all where i > 50  
  4.          
  5. System.out.printf("\t[Info] Query=%s :\n", query);  
  6.   
  7. DBCursor cur = coll.find(query);  
  8. while(cur.hasNext()) {  
  9.     System.out.println(cur.next());  
  10. }  
執行結果如下, 可以發現 i 皆大於 50 :


如果是 20 < i <= 30, 那也是一盤小菜拉 :
  1. DBCollection coll  = retvCollection("mydb");  
  2. BasicDBObject query = new BasicDBObject();  
  3. query = new BasicDBObject();  
  4.   
  5. query.put("i"new BasicDBObject("$gt"20).append("$lte"30));  // i.e.   20 < i <= 30  
  6.   
  7. DBCursor cur = coll.find(query);  
  8.   
  9. while(cur.hasNext()) {  
  10.     System.out.println(cur.next());  
  11. }  
- Creating An Index
在 MongoDB 也可以對 collection 設定 indexes, 而 index 的種類有 ascending (1) 與 descending (-1) ; 並且在設定 index 時你需要指定欄位. 底下代碼對 field "i" 設定 ascending index :
  1. coll.createIndex(new BasicDBObject("i"1));  // create index on "i", ascending  
- Getting a List of Indexes on a Collection
設定完 index, 你也可以從 collection 取出設定的 index 訊息, 參考下面代碼 :
  1. List list = coll.getIndexInfo();  
  2.   
  3.         for (DBObject o : list) {  
  4.             System.out.println(o);  
  5.         }  
執行後應該可以發現有一行為 :
{ "v" : 1 , "key" : { "i" : 1} , "ns" : "test.mydb" , "name" : "i_1"}

Quick Tour of the Administrative Functions :
- Getting A List of Databases
你可以透過下面代碼取出某個 MangoDB 上面已有的 database names :
  1. Mongo m = new Mongo();  
  2.   
  3.         for (String s : m.getDatabaseNames()) {  
  4.             System.out.println(s);  
  5.         }  
- Dropping A Database
如果你要 drop MongoDB 上面的某個 database, 則可以如下 :
  1. m.dropDatabase("my_new_db");  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...