玩轉mongodb(三):mongodb項目實戰(初戰)


說明:

    主要功能:對mongodb的集合做增刪改查。

    項目的運行環境:tomcat6、jdk8。

    所用技術:jsp/servlet、前端bootstrap。

    mongodb:personmap。

mongodb工具類:

    定義一個MongoDBUtil的枚舉類,枚舉類中定義一個instance實例。

    MongoDB工具類 Mongo實例代表了一個數據庫連接池,即使在多線程的環境中,一個Mongo實例對我們來說已經足夠。
    注意Mongo已經實現了連接池,並且是線程安全的。
    設計為單例模式, 因 MongoDB的Java驅動是線程安全的,對於一般的應用,只要一個Mongo實例即可。
    Mongo有個內置的連接池(默認為10個) 對於有大量寫和讀的環境中,為了確保在一個Session中使用同一個DB時,DB和DBCollection是絕對線程安全的

1 public enum MongoDBUtil {
2     /**
3      * 定義一個枚舉的元素,它代表此類的一個實例
4      */
5     instance;
6 }
View Code

    在MongoDBUtil類中,定義一個MongoClient對象,並根據IP和端口獲得該對象。

1 private MongoClient mongoClient;
2     static {
3         System.out.println("===============MongoDBUtil初始化========================");
4         // 從配置文件中獲取屬性值
5         String ip = "localhost";
6         int port = 27017;
7         instance.mongoClient = new MongoClient(ip, port);
8     }
View Code

     根據MongoClient對象,得到MongoDataBase對象和MongoConnection<Document>對象。

 1  /**
 2      * 獲取DB實例 - 指定DB
 3      * 
 4      * @param dbName
 5      * @return
 6      */
 7     public MongoDatabase getDB(String dbName) {
 8         if (dbName != null && !"".equals(dbName)) {
 9             MongoDatabase database = mongoClient.getDatabase(dbName);
10             return database;
11         }
12         return null;
13     }
14     /**
15      * 獲取collection對象 - 指定Collection
16      * 
17      * @param collName
18      * @return
19      */
20     public MongoCollection<Document> getCollection(String dbName, String collName) {
21         if (null == collName || "".equals(collName)) {
22             return null;
23         }
24         if (null == dbName || "".equals(dbName)) {
25             return null;
26         }
27         MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
28         return collection;
29     }
View Code

     工具類的查詢、插入、更新、刪除方法。

 1     /**條件查詢*/
 2     public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
 3         if(null!=filter){
 4             return coll.find(filter).iterator();
 5         }else{
 6             return coll.find().iterator();
 7         }
 8     }
 9     /**插入一條數據*/
10     public void insert(MongoCollection<Document> coll,Document doc){
11         coll.insertOne(doc);
12     }
13     
14     /**更新一條數據*/
15     public void update(MongoCollection<Document> coll,Document querydoc,Document updatedoc){
16         coll.updateMany(querydoc, updatedoc);
17     }
18 
19     /**刪除一條數據*/
20     public void delete(MongoCollection<Document> coll,Document doc){
21         coll.deleteMany(doc);
22     }
View Code

 

 項目中的增刪改查:

    插入:對應MongoDB中腳本的db.getCollection('person').insert({"name":"ryan1","age":21})

 1     String name = request.getParameter("name");
 2     Double age = Double.valueOf(request.getParameter("age"));
 3     
 4     String dbName = "personmap";
 5         String collName = "person";
 6         MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
 7         
 8         Document doc = new Document();
 9         doc.put("name", name);
10         doc.put("age", age);
11         MongoDBUtil.instance.insert(coll, doc);
12         
13         PrintWriter out = response.getWriter();
14         out.write("insert success!");
插入功能的servlet
 1 <div class="panel    panel-warning" style="width:20%">
 2     <div class="panel-heading">刪除文檔</div>
 3     <div class="panel-body">
 4         <form action="InsertPerson">
 5             <input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
 6             <br/>
 7             <input type="text" name="age" class="form-control" placeholder="age" aria-describedby="basic-addon1">
 8             <br/>
 9             <button type="submit" class="btn btn-default">插入</button>
10         </form>
11     </div>
12 </div>
插入功能的jsp

    

    更新:對應MongoDB中腳本的db.getCollection('person').update({"name":"ryan1"}{"$set":{"age":22}})

 1     String queryname = request.getParameter("queryname");
 2     Double updateage = Double.valueOf(request.getParameter("updateage"));
 3     
 4     String dbName = "personmap";
 5     String collName = "person";
 6     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
 7         
 8     Document querydoc = new Document();
 9     querydoc.put("name", queryname);
10 
11     Document updatedoc = new Document();
12     updatedoc.put("name", queryname);
13     updatedoc.put("age", updateage);
14                 
15     MongoDBUtil.instance.update(coll, querydoc , new Document("$set",updatedoc));
16         
17         PrintWriter out = response.getWriter();
18         out.write("update success!");
更新功能的servlet
 1 <div class="panel    panel-warning" style="width:20%">
 2     <div class="panel-heading">根據name更新age</div>
 3     <div class="panel-body">
 4         <form action="UpdatePerson">
 5             <input type="text" name="queryname" class="form-control" placeholder="queryname" aria-describedby="basic-addon1">
 6             <br/>
 7             <input type="text" name="updateage" class="form-control" placeholder="updateage" aria-describedby="basic-addon1">
 8             <br/>
 9             <button type="submit" class="btn btn-default">更新</button>
10     </form>
11     </div>
12 </div>
更新功能的jsp

    

    刪除:對應MongoDB中腳本的db.getCollection('person').remove({"name":"ryan1"})

 1     String name = request.getParameter("name");
 2     
 3     String dbName = "personmap";
 4     String collName = "person";
 5     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
 6         
 7     Document doc = new Document();
 8     doc.put("name", name);
 9 
10     MongoDBUtil.instance.delete(coll, doc);
11         
12     PrintWriter out = response.getWriter();
13     out.write("delete success!");
刪除功能的servlet
 1 <div class="panel    panel-warning" style="width:20%">
 2     <div class="panel-heading">刪除文檔</div>
 3     <div class="panel-body">
 4         <form action="DeletePerson">
 5             <input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
 6             <br/>
 7             <button type="submit" class="btn btn-default">刪除</button>
 8         </form>
 9     </div>
10 </div>
刪除功能的jsp

    

    查找:對應MongoDB中腳本的db.getCollection('person').find({})

 1     String dbName = "personmap";
 2     String collName = "person";
 3     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
 4         
 5     List<Person> personList = new ArrayList<Person>();
 6     // 查詢所有
 7     //Bson filter = Filters.eq("name", "ryan1");
 8     Bson filter = null;
 9     MongoCursor<Document> cursor = MongoDBUtil.instance.find(coll, filter);
10     while(cursor.hasNext()){
11         Document tempdoc = cursor.next();
12         Person person = new Person();
13         person.set_id(tempdoc.get("_id").toString());
14         person.setName(tempdoc.get("name").toString());
15 person.setAge(Double.valueOf(tempdoc.get("age").toString()));
16             personList.add(person);
17     }
18         
19     Gson gson = new Gson();
20         
21     PrintWriter out = response.getWriter();
22     out.write(gson.toJson(personList));
查找功能的servlet
 1 <div class="panel panel-warning" style="width:50%">
 2     <div class="panel-heading">查找全部數據</div>
 3     <div class="panel-body">
 4     <table data-toggle="table" 
 5                data-url="FindPerson"
 6                data-classes="table table-hover table-condensed"
 7                data-striped="true">
 8         <thead>
 9             <tr>
10                 <th class="col-xs-2" data-field="_id">_id</th>
11                 <th class="col-xs-2" data-field="name">name</th>
12                 <th class="col-xs-2" data-field="age">age</th>
13             </tr>
14         </thead>
15     </table>
16     </div>
17 </div>
查找功能的jsp

    

    源代碼下載

 

  喜歡請微信掃描下面二維碼,關注我公眾號--“精修Java”,做一些實戰項目中的問題和解決方案分享。 

 


免責聲明!

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



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