import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.bson.types.ObjectId;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.mongodb.BasicDBObject;import com.mongodb.Bytes;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.Mongo;import com.mongodb.MongoClient;import com.mongodb.MongoException;import com.mongodb.QueryOperators;import com.mongodb.ReadPreference;import com.mongodb.ServerAddress;import com.mongodb.gridfs.GridFS;import com.mongodb.gridfs.GridFSDBFile;import com.mongodb.gridfs.GridFSInputFile;import com.mongodb.util.JSON;/** * @Title: MongoDB.java * @Package * @Description: TODO(用一句話描述該檔案做什麼) * @author 石華才 * @date 2013-1-17 下午05:00:20 *//** * @ClassName: MongoDB * @Description: TODO(這裡用一句話描述這個類的作用) * @author 石華才 * @date 2013-1-17 下午05:00:20 */@SuppressWarnings("deprecation")public class MongoDB {private Mongo mg = null; private DB db; private DBCollection users;public static void main(String[] args){try{//資料庫檔案的位置取決於mongo服務啟動時指定的位置Mongo mongo = new Mongo(); //查詢所有的Database for (String name : mongo.getDatabaseNames()) { System.out.println("dbName: " + name); } //串連指定的資料庫DB db = mongo.getDB("copytest");//查詢所有的聚集集合(查詢copytest庫下的所有表) for (String name : db.getCollectionNames()) { System.out.println("collectionName: " + name); } //串連指定的表(集合)DBCollection testCollection = db.getCollection("foo");DBCursor cur = testCollection.find();while(cur.hasNext()){System.out.println(cur.next());}System.out.println(cur.count()); System.out.println(cur.getCursorId()); System.out.println(JSON.serialize(cur));}catch(Exception e){System.out.println(e);}}@Before public void init() { try { mg = new Mongo(); //mg = new Mongo("localhost", 27017); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } //擷取temp DB;如果預設沒有建立,mongodb會自動建立 db = mg.getDB("temp"); //擷取users DBCollection;如果預設沒有建立,mongodb會自動建立 users = db.getCollection("users"); }/** * <b>function:</b> 查詢所有資料 * @author hoojo * @createDate 2011-6-2 下午03:22:40 */@Testpublic void queryAll() { print("查詢users的所有資料:"); //db遊標 DBCursor cur = users.find(); while (cur.hasNext()) { print(cur.next()); }}@Testpublic void add() { //先查詢所有資料 queryAll(); print("count: " + users.count()); DBObject user = new BasicDBObject(); user.put("name", "hoojo2"); user.put("age", 242); users.save(user);//儲存,getN()擷取影響行數 print(users.save(user).getN()); //擴充欄位,隨意添加欄位,不影響現有資料 user.put("sex", "男"); print(users.save(user).getN()); //添加多條資料,傳遞Array對象 print(users.insert(user, new BasicDBObject("name", "tom")).getN()); //添加List集合 List<DBObject> list = new ArrayList<DBObject>(); list.add(user); DBObject user2 = new BasicDBObject("name", "lucy"); user.put("age", 22); list.add(user2); //添加List集合 print(users.insert(list).getN()); //查詢下資料,看看是否添加成功 print("count: " + users.count()); queryAll();}@Testpublic void remove() { queryAll(); print("刪除id = 4de73f7acd812d61b4626a77:" + users.remove(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).getN()); print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN());}@Testpublic void modify() { print("修改:" + users.update(new BasicDBObject("_id", new ObjectId("4dde25d06be7c53ffbd70906")), new BasicDBObject("age", 99)).getN()); print("修改:" + users.update( new BasicDBObject("_id", new ObjectId("4dde2b06feb038463ff09042")), new BasicDBObject("age", 121), true,//如果資料庫不存在,是否添加 false//多條修改 ).getN()); print("修改:" + users.update( new BasicDBObject("name", "haha"), new BasicDBObject("name", "dingding"), true,//如果資料庫不存在,是否添加 true//false只修改第一天,true如果有多條就不修改 ).getN()); //當資料庫不存在就不修改、不添加資料,當多條資料就不修改 //print("修改多條:" + coll.updateMulti(new BasicDBObject("_id", new ObjectId("4dde23616be7c19df07db42c")), new BasicDBObject("name", "199")));}//mongoDB不支援聯集查詢、子查詢,這需要我們自己在程式中完成。將查詢的結果集在Java查詢中進行需要的過濾即可。@Testpublic void query() { //查詢所有 //queryAll(); //查詢id = 4de73f7acd812d61b4626a77 print("find id = 4de73f7acd812d61b4626a77: " + users.find(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).toArray()); //查詢age = 24 print("find age = 24: " + users.find(new BasicDBObject("age", 24)).toArray()); //強制使用某個索引 //users.setHintFields(lst); //查詢age >= 24 print("find age >= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24))).toArray()); print("find age <= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$lte", 24))).toArray()); print("查詢age!=25:" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray()); print("查詢age in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray()); print("查詢age not in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray()); print("查詢age exists 排序:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray()); print("只查詢age屬性:" + users.find(null, new BasicDBObject("age", true)).toArray()); print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2).toArray()); print("只查屬性:" + users.find(null, new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray()); //只查詢一條資料,多條去第一條 print("findOne: " + users.findOne()); print("findOne: " + users.findOne(new BasicDBObject("age", 26))); print("findOne: " + users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true))); //查詢修改、刪除 print("findAndRemove 查詢age=25的資料,並且刪除: " + users.findAndRemove(new BasicDBObject("age", 25))); //查詢age=26的資料,並且修改name的值為Abc print("findAndModify: " + users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "Abc"))); print("findAndModify: " + users.findAndModify( new BasicDBObject("age", 28), //查詢age=28的資料 new BasicDBObject("name", true), //查詢name屬性 new BasicDBObject("age", true), //按照age排序 false, //是否刪除,true表示刪除 new BasicDBObject("name", "Abc"), //修改的值,將name修改成Abc true, true)); queryAll();}@Testpublic void testOthers() { DBObject user = new BasicDBObject(); user.put("name", "hoojo"); user.put("age", 24); //JSON 對象轉換 print("serialize: " + JSON.serialize(user)); //還原序列化 print("parse: " + JSON.parse("{ \"name\" : \"hoojo\" , \"age\" : 24}")); print("判斷temp Collection是否存在: " + db.collectionExists("temp")); //如果不存在就建立 if (!db.collectionExists("temp")) { DBObject options = new BasicDBObject(); options.put("size", 20); options.put("capped", 20); options.put("max", 20); print(db.createCollection("account", options)); } //設定db為唯讀 db.setReadOnly(true); //唯讀不能寫入資料 db.getCollection("test").save(user);}@After public void destory() { if (mg != null) mg.close(); mg = null; db = null; users = null; System.gc(); } public void print(Object o) { System.out.println(o); } @Test public void savePicture(){ try{ //如果沒有,自動建立 DB db = mg.getDB("beijingVector"); //DBCollection collection = db.getCollection("beijingVector");GridFS gridFS= new GridFS(db);GridFSInputFile gfs = gridFS.createFile(new FileInputStream(new File("E:\\瓦片資料\\北京影像\\L11\\R000002fc\\C0000069b.jpg")));gfs.put("filename", "aaaaaaaaaaa");gfs.save(); }catch (Exception e) {// TODO: handle exception} } @Test public void getPictureByName(){ try{ //如果沒有,自動建立 DB db = mg.getDB("beijingVector");GridFS gridFS= new GridFS(db);/*DBObject query = new BasicDBObject("filename", fileName);GridFSDBFile gridFSDBFile = myFS.findOne(query);//根據ID查詢DBObject query = new BasicDBObject("_id", id);GridFSDBFile gridFSDBFile = myFS.findOne(query);*/GridFSDBFile gridFSDBFile = gridFS.findOne("aaaaaaaaaaa");//直接查詢其檔案名稱gridFSDBFile.writeTo("c:\test.png");InputStream is = gridFSDBFile.getInputStream();int buffer_size = 1024;FileOutputStream fos = new FileOutputStream(new File("C:\\cc.png"));final byte[] b = new byte[buffer_size];int read;while ((read = is.read(b)) != -1) {fos.write(b, 0, read);}is.close();fos.flush();fos.close();if(gridFSDBFile != null)return; }catch (Exception e) {} } //以二進位的方式進行儲存 @Test public void savePicByDoc(){ try{ //如果沒有,自動建立 DB db = mg.getDB("beijingVector"); DBCollection collection = db.getCollection("beijingVector"); InputStream is = new FileInputStream(new File("E:\\瓦片資料\\北京影像\\L11\\R000002fc\\C0000069b.jpg")); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = is.read(buffer))) { output.write(buffer, 0, n); } byte[] imgByte = output.toByteArray(); DBObject user = new BasicDBObject(); user.put("name", "aa"); user.put("img", imgByte); collection.save(user); //批量插入 //collection.insert(list); }catch (Exception e) {// TODO: handle exception} } @Test public void getPicFromByte(){ try{ //如果沒有,自動建立 DB db = mg.getDB("beijingVector"); DBCollection collection = db.getCollection("beijingVector"); List<DBObject> list = collection.find(new BasicDBObject("name", "aa")).toArray(); if(list != null&& list.size() > 0){ byte[] b = (byte[]) list.get(0).get("img"); //ByteArrayInputStream bas = new ByteArrayInputStream(b); FileOutputStream fos = new FileOutputStream(new File("c:\\a.png")); fos.write(b, 0, b.length); fos.flush(); fos.close(); } }catch (Exception e) {} } /** * * @Title: ensureIndex * @Params : * @Description: TODO(建立索引) * @return void 傳回型別 * @author 石華才 * @throws */ @Test public void ensureIndex(){ try{ //如果沒有,自動建立 DB db = mg.getDB("beijingVector"); DBCollection collection = db.getCollection("beijingVector"); //單欄位索引 collection.ensureIndex(new BasicDBObject("name", 1), "nameIndex", true); //複合索引 BasicDBObject obj = new BasicDBObject(); obj.put("Age", 1);//升序 obj.put("Name", -1);//降序 collection.ensureIndex(obj); List<DBObject> list = collection.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } }catch (Exception e) {} } /** * @Title: 配置主從叢集(主從複製) * @Params : * @Description: TODO(測試時,請不要在預設的local集合中添加資料,否則看不到效果,預設不同步local中的資料) * @return void 傳回型別 * @author 石華才 * @throws */ @Test public void addDataToMaster() throws UnknownHostException{ { MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 1000)); DB db = mongoClient.getDB("testMasterDB"); DBCollection collection = db.getCollection("testMasterCollection"); DBObject dbObject = new BasicDBObject(); dbObject.put("name", "測試用力4"); collection.save(dbObject); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject obj = cursor.next(); System.out.println(obj.toString()); } mongoClient.close(); } //系統預設10s同步一次,故下面代碼要在十秒以後才能執行,請直接在mongoVUE中查看效果 { MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 10002)); DB db = mongoClient.getDB("testMasterDB"); DBCollection collection = db.getCollection("testMasterCollection"); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject obj = cursor.next(); System.out.println(obj.toString()); } mongoClient.close(); } } /** * @Title: 配置複本集(活躍節點與備份節點之間也能自動複製資料) * @Params : * @Description: TODO() * @return void 傳回型別 * @author 石華才 * @throws */ @Test public void addDataToReplSet() throws UnknownHostException{ { //不能串連非活躍節點,原因暫不明,shell只能串連,不能插入資料,報not master錯誤 MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 10001)); //設定Secondary節點可讀,在Secondary裡面也需要做如下設定 mongoClient.setReadPreference(ReadPreference.secondaryPreferred()); DB db = mongoClient.getDB("testReplSetDB"); DBCollection collection = db.getCollection("testReplSetCollection"); DBObject dbObject = new BasicDBObject(); dbObject.put("name", "etrhgw文替我太re"); collection.save(dbObject); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject obj = cursor.next(); System.out.println(obj.toString()); } mongoClient.close(); } { MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 10002)); mongoClient.setReadPreference(ReadPreference.secondaryPreferred()); DB db = mongoClient.getDB("testReplSetDB"); DBCollection collection = db.getCollection("testReplSetCollection"); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject obj = cursor.next(); System.out.println(obj.toString()); } mongoClient.close(); } }}