java 實現操作mongodb的串連,增刪查改

來源:互聯網
上載者:User
java 實現操作mongodb的串連,增刪查改

mongodb的jar包下載
java mongodb 驅動
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/
我下載的是(mongo-java-driver-3.0.1.jar)

java 實現mongodb的串連關閉操作,寫一個mongodbHelper

package com.java.dao;import com.mongodb.MongoClient;import com.mongodb.client.MongoDatabase;public class MongoHelper {        static final String DBName = "weibo";        static final String ServerAddress = "127.0.0.1";         static final int PORT = 27017;        public MongoHelper(){        }        public MongoClient getMongoClient( ){            MongoClient mongoClient = null;            try {                  // 串連到 mongodb 服務                mongoClient = new MongoClient(ServerAddress, PORT);                 System.out.println("Connect to mongodb successfully");            } catch (Exception e) {                System.err.println(e.getClass().getName() + ": " + e.getMessage());            }            return mongoClient;        }        public MongoDatabase getMongoDataBase(MongoClient mongoClient) {              MongoDatabase mongoDataBase = null;            try {                  if (mongoClient != null) {                        // 串連到資料庫                    mongoDataBase = mongoClient.getDatabase(DBName);                      System.out.println("Connect to DataBase successfully");                } else {                      throw new RuntimeException("MongoClient不能夠為空白");                  }              } catch (Exception e) {                  e.printStackTrace();              }            return mongoDataBase;        }          public void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) {              if (mongoDataBase != null) {                  mongoDataBase = null;              }              if (mongoClient != null) {                  mongoClient.close();              }              System.out.println("CloseMongoClient successfully");          }  }

串連成功後進行增刪查改操作
這是基本增刪查改的介面

package com.java.dao;import java.util.Map;import org.bson.Document;import com.mongodb.BasicDBObject;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoDatabase;/** * Dao 層介面 *  */public interface MongoDao {    /**     * Get Data BY ID     *      * @param db     * @param table     * @param Id     * @throws Exception      */    public Map<String,Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception;    /**     * Insert Data     *      * @param db     * @param table     * @param document     */    public boolean insert(MongoDatabase db, String table, Document doc);    /**     * Delete Many Data.if doc is empty will delete all Data     *      * @param db     * @param table     * @param document     */    public boolean delete(MongoDatabase db, String table, BasicDBObject doc);    /**     * Update All Data     *      * @param db     * @param table     * @param oldDoc     * @param newDoc     */    public boolean update(MongoDatabase db, String table, BasicDBObject oldDoc,            BasicDBObject newDoc);}

實現上面的介面並且擴充方法

package com.java.dao;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.bson.Document;import com.java.exception.CustomException;import com.java.service.JsonStrToMap;import com.mongodb.BasicDBObject;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.result.DeleteResult;import com.mongodb.client.result.UpdateResult;/** * 實現介面 * @author iiip * */public class MongoDaoImpl implements MongoDao {    @Override    public Map<String,Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception{        MongoCollection<Document> collection = db.getCollection(table);        BasicDBObject query = new BasicDBObject("_id", Id);        //  DBObject介面和BasicDBObject對象:表示一個具體的記錄,BasicDBObject實現了DBObject,是key-value的資料結構,用起來和HashMap是基本一致的。        FindIterable<Document> iterable = collection.find(query);//      for (Document dd : iterable) {//          int dudu = dd.getInteger("上海"); // 讀取響應的資料//          System.out.println("dudududu:"+dudu);//      }        Map<String,Integer> jsonStrToMap = null;        MongoCursor<Document> cursor = iterable.iterator();        while (cursor.hasNext()) {            Document user = cursor.next();            String jsonString = user.toJson();            jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);//這裡用到我自己寫的方法,主要是包json字串轉換成map格式,為後面做準備,方法放在後面        }        System.out.println("檢索ID完畢");        return jsonStrToMap;    }    /**     * 根據一個doc,來檢索,當doc是空的時候檢索全部     * @param db     * @param table     * @param doc     */    public List<Map<String,Integer>>  queryByDoc(MongoDatabase db, String table, BasicDBObject doc) {        MongoCollection<Document> collection = db.getCollection(table);        FindIterable<Document> iterable = collection.find(doc);         /**          * 1. 擷取迭代器FindIterable<Document>          * 2. 擷取遊標MongoCursor<Document>          * 3. 通過遊標遍曆檢索出的文檔集合          * */          List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();        MongoCursor<Document> cursor = iterable.iterator();        while (cursor.hasNext()) {            Document user = cursor.next();            String jsonString = user.toJson();            Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);            list.add(jsonStrToMap);        }        System.out.println("檢索doc完畢");        return list;    }    /**     *  檢索全部並返回迭代器     * @param db     * @param table     */    public List<Map<String,Integer>> queryAll(MongoDatabase db, String table) {        MongoCollection<Document> collection = db.getCollection(table);        FindIterable<Document> iterable = collection.find();        List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();        MongoCursor<Document> cursor = iterable.iterator();        while (cursor.hasNext()) {            Document user = cursor.next();            String jsonString = user.toJson();            Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);            list.add(jsonStrToMap);        }        System.out.println("檢索全部完畢");        return list;    }    /**     * 便利迭代器FindIterable<Document>      */    public void printFindIterable(FindIterable<Document> iterable){        MongoCursor<Document> cursor = iterable.iterator();        while (cursor.hasNext()) {            Document user = cursor.next();            System.out.println(user.toJson());        }        cursor.close();    }    @Override    public boolean insert(MongoDatabase db, String table, Document document) {        MongoCollection<Document> collection = db.getCollection(table);        collection.insertOne(document);        long count = collection.count(document);//      System.out.println(collection.getNamespace());//weibo.area//      System.out.println(collection.getClass());//class com.mongodb.MongoCollectionImpl//      System.out.println(collection.getDocumentClass());//class org.bson.Document//      System.out.println(collection.getWriteConcern());//WriteConcern{w=1, wtimeout=0, fsync=false, j=false//      System.out.println(collection.getWriteConcern().getW());//1        System.out.println("count: "+count);        if(count == 1){            System.out.println("文檔插入成功");            return true;        }else{            System.out.println("文檔插入成功");            return false;        }    }    /**     * insert many     * @param db     * @param table     * @param document     */    public boolean insertMany(MongoDatabase db, String table, List<Document> documents ) {        MongoCollection<Document> collection = db.getCollection(table);        long preCount = collection.count();        collection.insertMany(documents);        long nowCount = collection.count();        System.out.println("插入的數量: "+(nowCount-preCount));        if((nowCount-preCount) == documents.size() ){            System.out.println("文檔插入多個成功");            return true;        }else{            System.out.println("文檔插入多個失敗");            return false;        }    }    @Override    public boolean delete(MongoDatabase db, String table, BasicDBObject document) {        MongoCollection<Document> collection = db.getCollection(table);        DeleteResult deleteManyResult = collection.deleteMany(document);        long deletedCount = deleteManyResult.getDeletedCount();        System.out.println("刪除的數量: "+deletedCount);        if(deletedCount > 0){            System.out.println("文檔刪除多個成功");            return true;        }else{            System.out.println("文檔刪除多個失敗");            return false;        }    }    /**     * 刪除一個     * @param db     * @param table     * @param document     */    public boolean deleteOne(MongoDatabase db, String table, BasicDBObject document) {        MongoCollection<Document> collection = db.getCollection(table);        DeleteResult deleteOneResult = collection.deleteOne(document);        long deletedCount = deleteOneResult.getDeletedCount();        System.out.println("刪除的數量: "+deletedCount);        if(deletedCount == 1){            System.out.println("文檔刪除一個成功");            return true;        }else{            System.out.println("文檔刪除一個失敗");            return false;        }    }    @Override    public boolean update(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {            MongoCollection<Document> collection = db.getCollection(table);               UpdateResult updateManyResult = collection.updateMany(whereDoc, new Document("$set",updateDoc));              long modifiedCount = updateManyResult.getModifiedCount();             System.out.println("修改的數量: "+modifiedCount);            if (modifiedCount > 0){                System.out.println("文檔更新多個成功");                return true;            }else{                System.out.println("文檔更新失敗");                return false;            }    }    /**     * update one Data     * @param db     * @param table     * @param whereDoc     * @param updateDoc     */    public boolean updateOne(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {            MongoCollection<Document> collection = db.getCollection(table);               UpdateResult updateOneResult = collection.updateOne(whereDoc, new Document("$set",updateDoc));              long modifiedCount = updateOneResult.getModifiedCount();             System.out.println("修改的數量: "+modifiedCount);             if(modifiedCount == 1){                System.out.println("文檔更新一個成功");                 return true;             }else{                System.out.println("文檔更新失敗");                 return false;             }    }    /**     * create collection     * @param db     * @param table     */    public void createCol(MongoDatabase db, String table) {         db.createCollection(table);        System.out.println("集合建立成功");    }    /**     * drop a collection     * @param db     * @param table     */    public void dropCol(MongoDatabase db, String table) {        db.getCollection(table).drop();        System.out.println("集合刪除成功");    }}

前面用到的一個類方法JsonStrToMap.jsonStrToMap

package com.java.service;import java.util.HashMap;import java.util.Map;import com.mongodb.util.JSON;public class JsonStrToMap {    /**     * json 字串轉化為map格式     * @param jsonString     * @return     */    public static Map<String, Integer> jsonStrToMap(String jsonString) {        Object parseObj = JSON.parse(jsonString); // 還原序列化 把json 轉化為對象        Map<String, Integer> map = (HashMap<String, Integer>) parseObj; // 把對象轉化為map        return map;    }}

測試方法

package com.java.dao;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.bson.Document;import com.mongodb.BasicDBObject;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoDatabase;import com.mongodb.util.JSON;/** * 測試類別 * @author koo * */public class MainMonHelperImpl {    public static void main(String[] args) {        MongoHelper mongoHelper = new MongoHelper();        MongoClient mongoClient = mongoHelper.getMongoClient();        MongoDatabase mongoDataBase = mongoHelper.getMongoDataBase(mongoClient);        MongoDaoImpl mongoDaoImpl = new MongoDaoImpl();// *  直接用BasicDBObject進行CRUD//      mongoDaoImpl.insert(mongoDataBase, table, new Document(areaMap));//插入document//      mongoDaoImpl.queryByID(mongoDataBase, table, 1);//檢索event_id,注意id類型是字串還是int//      BasicDBObject document2 = new BasicDBObject("likes",1000);//      document2.append("event_id", "55");//      mongoDaoImpl.queryByDoc(mongoDataBase, table, document2);//檢索doc,可以根據doc(key,value)來尋找,當doc是空的時候,檢索全部//      mongoDaoImpl.queryAll(mongoDataBase, table); //查詢全部//      BasicDBObject document3 = new BasicDBObject("likes",200);//      mongoDaoImpl.delete(mongoDataBase, table, document3);//刪除doc 的全部資訊,當doc 是空,則刪除全部//      BasicDBObject document3 = new BasicDBObject("likes", 1000);//      mongoDaoImpl.deleteOne(mongoDataBase, table, document3);//刪除doc 的一個資訊//      更新文檔   將文檔中likes=100的文檔修改為likes=200   //      BasicDBObject whereDoc = new BasicDBObject("likes",1000);//      BasicDBObject updateDoc = new BasicDBObject("likes",255);//      mongoDaoImpl.update(mongoDataBase, table, whereDoc, updateDoc);//更新全部,尋找到oldDoc的資料,更新newDoc的資料//      BasicDBObject whereDoc = new BasicDBObject("likes",255);//      BasicDBObject updateDoc = new BasicDBObject("event_id",205);//      mongoDaoImpl.updateOne(mongoDataBase, table, whereDoc, updateDoc);//更新全部,尋找到oldDoc的資料,更新newDoc的資料//------------------------------------------------        /**         * 使用map 進行CRUD操作         *///      System.out.println("測試map");//      Map<String, Object> areaMap1 = new HashMap<String,Object>();//      areaMap1.put("_id", 2);//      areaMap1.put("北京", 5);//      areaMap1.put("上海", 14);//      areaMap1.put("廣州",8);//      areaMap1.put("深圳",0.5);         //把map還原序列化//      System.out.println("map parse: " + JSON.parse(JSON.serialize(areaMap)));          // 根據map 到mongodb查詢//     FindIterable<Document> queryByDocResult = mongoDaoImpl.queryByDoc(mongoDataBase, areaTable, new BasicDBObject(areaMap1));//     mongoDaoImpl.printFindIterable(queryByDocResult);        //   插入map 到mongodb//      mongoDaoImpl.insert(mongoDataBase, areaTable, new Document(areaMap1));//      Map<String, Object> areaMap2 = new HashMap<String,Object>();//      Map<String, Object> areaMap3 = new HashMap<String,Object>();//      areaMap2.put("_id", 10);//      areaMap2.put("北京", 5);////      areaMap3.put("_id", 11);//      areaMap3.put("北京", 5);//      List<Document> docList = new ArrayList<Document>();//      docList.add(new Document(areaMap2));//      docList.add(new Document(areaMap3));//      mongoDaoImpl.insertMany(mongoDataBase, areaTable, docList);        //   根據map 刪除mongodb//      mongoDaoImpl.delete(mongoDataBase, areaTable, new BasicDBObject(areaMap1));//      mongoDaoImpl.deleteOne(mongoDataBase, areaTable, new BasicDBObject(areaMap1));        //根據map 更新mongodb//      Map<String, Object> updateDoc = new HashMap<String,Object>();//      Map<String, Object> wehereDoc = new HashMap<String,Object>();//      wehereDoc.put("_id", 4);//      updateDoc.put("上海",25);//      mongoDaoImpl.update(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));//      mongoDaoImpl.updateOne(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));        //檢索全部//      FindIterable<Document> queryAllResult = mongoDaoImpl.queryAll(mongoDataBase, areaTable);//      mongoDaoImpl.printFindIterable(queryAllResult);//      mongoHelper.closeMongoClient(mongoDataBase,mongoClient);    }}

參考:
mongoUtil java heleper
http://blog.csdn.net/guoxingege/article/details/47439581

文法:
http://www.runoob.com/mongodb/mongodb-java.html

文檔
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

java mongodb 驅動
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.