玩转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是绝对线程安全的
public enum MongoDBUtil {
/**
* 定义一个枚举的元素,它代表此类的一个实例
*/
instance;
}
在MongoDBUtil类中,定义一个MongoClient对象,并根据IP和端口获得该对象。
private MongoClient mongoClient;
static {
System.out.println("===============MongoDBUtil初始化========================");
// 从配置文件中获取属性值
String ip = "localhost";
int port = 27017;
instance.mongoClient = new MongoClient(ip, port);
}
根据MongoClient对象,得到MongoDataBase对象和MongoConnection<Document>对象。
/**
* 获取DB实例 - 指定DB
*
* @param dbName
* @return
*/
public MongoDatabase getDB(String dbName) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* 获取collection对象 - 指定Collection
*
* @param collName
* @return
*/
public MongoCollection<Document> getCollection(String dbName, String collName) {
if (null == collName || "".equals(collName)) {
return null;
}
if (null == dbName || "".equals(dbName)) {
return null;
}
MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
return collection;
}
工具类的查询、插入、更新、删除方法。
/**条件查询*/
public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
if(null!=filter){
return coll.find(filter).iterator();
}else{
return coll.find().iterator();
}
}
/**插入一条数据*/
public void insert(MongoCollection<Document> coll,Document doc){
coll.insertOne(doc);
} /**更新一条数据*/
public void update(MongoCollection<Document> coll,Document querydoc,Document updatedoc){
coll.updateMany(querydoc, updatedoc);
} /**删除一条数据*/
public void delete(MongoCollection<Document> coll,Document doc){
coll.deleteMany(doc);
}
项目中的增删改查:
插入:对应MongoDB中脚本的db.getCollection('person').insert({"name":"ryan1","age":21})
String name = request.getParameter("name");
Double age = Double.valueOf(request.getParameter("age"));
String dbName = "personmap";
String collName = "person";
MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
Document doc = new Document();
doc.put("name", name);
doc.put("age", age);
MongoDBUtil.instance.insert(coll, doc);
PrintWriter out = response.getWriter();
out.write("insert success!");
插入功能的servlet
<div class="panel panel-warning" style="width:20%">
<div class="panel-heading">删除文档</div>
<div class="panel-body">
<form action="InsertPerson">
<input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
<br/>
<input type="text" name="age" class="form-control" placeholder="age" aria-describedby="basic-addon1">
<br/>
<button type="submit" class="btn btn-default">插入</button>
</form>
</div>
</div>
插入功能的jsp

更新:对应MongoDB中脚本的db.getCollection('person').update({"name":"ryan1"}{"$set":{"age":22}})
String queryname = request.getParameter("queryname");
Double updateage = Double.valueOf(request.getParameter("updateage"));
String dbName = "personmap";
String collName = "person";
MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
Document querydoc = new Document();
querydoc.put("name", queryname);
Document updatedoc = new Document();
updatedoc.put("name", queryname);
updatedoc.put("age", updateage);
MongoDBUtil.instance.update(coll, querydoc , new Document("$set",updatedoc));
PrintWriter out = response.getWriter();
out.write("update success!");
更新功能的servlet
<div class="panel panel-warning" style="width:20%">
<div class="panel-heading">根据name更新age</div>
<div class="panel-body">
<form action="UpdatePerson">
<input type="text" name="queryname" class="form-control" placeholder="queryname" aria-describedby="basic-addon1">
<br/>
<input type="text" name="updateage" class="form-control" placeholder="updateage" aria-describedby="basic-addon1">
<br/>
<button type="submit" class="btn btn-default">更新</button>
</form>
</div>
</div>
更新功能的jsp

删除:对应MongoDB中脚本的db.getCollection('person').remove({"name":"ryan1"})
String name = request.getParameter("name");
String dbName = "personmap";
String collName = "person";
MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
Document doc = new Document();
doc.put("name", name);
MongoDBUtil.instance.delete(coll, doc);
PrintWriter out = response.getWriter();
out.write("delete success!");
删除功能的servlet
<div class="panel panel-warning" style="width:20%">
<div class="panel-heading">删除文档</div>
<div class="panel-body">
<form action="DeletePerson">
<input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
<br/>
<button type="submit" class="btn btn-default">删除</button>
</form>
</div>
</div>
删除功能的jsp

查找:对应MongoDB中脚本的db.getCollection('person').find({})
String dbName = "personmap";
String collName = "person";
MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName); List<Person> personList = new ArrayList<Person>();
// 查询所有
//Bson filter = Filters.eq("name", "ryan1");
Bson filter = null;
MongoCursor<Document> cursor = MongoDBUtil.instance.find(coll, filter);
while(cursor.hasNext()){
Document tempdoc = cursor.next();
Person person = new Person();
person.set_id(tempdoc.get("_id").toString());
person.setName(tempdoc.get("name").toString());
person.setAge(Double.valueOf(tempdoc.get("age").toString()));
personList.add(person);
} Gson gson = new Gson(); PrintWriter out = response.getWriter();
out.write(gson.toJson(personList));
查找功能的servlet
<div class="panel panel-warning" style="width:50%">
<div class="panel-heading">查找全部数据</div>
<div class="panel-body">
<table data-toggle="table"
data-url="FindPerson"
data-classes="table table-hover table-condensed"
data-striped="true">
<thead>
<tr>
<th class="col-xs-2" data-field="_id">_id</th>
<th class="col-xs-2" data-field="name">name</th>
<th class="col-xs-2" data-field="age">age</th>
</tr>
</thead>
</table>
</div>
</div>
查找功能的jsp

喜欢请微信扫描下面二维码,关注我公众号--“精修Java”,做一些实战项目中的问题和解决方案分享。

玩转mongodb(三):mongodb项目实战(初战)的更多相关文章
- 转:手把手教你如何玩转Solr(包含项目实战)
原文地址:手把手教你如何玩转Solr(包含项目实战) 参考原文
- VS2013中Nuget程序包管理器控制台使用入门(三)-项目实战(原创)
VS2013中Nuget程序包管理器控制台使用入门(三)-项目实战 1.给指定项目安装Newtonsoft.Json ,Version 4.5.11 PM> Install-Package Ne ...
- MongoDB (三) MongoDB 安装
MongoDB安装在Windows上 在 Windows上,首先要安装 MongoDB下载最新发布的MongoDB: http://www.mongodb.org/downloads 确保得到正确的版 ...
- 快速掌握mongoDB(三)——mongoDB的索引详解
1 mongoDB索引的管理 本节介绍mongoDB中的索引,熟悉mysql/sqlserver等关系型数据库的小伙伴应该都知道索引对优化数据查询的重要性.我们先简单了解一下索引:索引的本质就是一个排 ...
- 手把手教你如何玩转Solr(包含项目实战)
一:Solr简介 Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口.用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引 ...
- .net转php laraval框架学习系列(三)项目实战---Route&Controllers
本章来学习laravel的路由 一个简单的路由列子 Route::get('/', function() { return 'Hello World'; }); 路由的写法和Node的风格很相似.上面 ...
- selenium3 web自动化测试框架 三:项目实战中PO模型的设计与封装
po模型设计思想 Page Object 模式主要是将每个页面设计为一个class,其中包含页面中的需要测试的元素(按钮,输入框,标题等),这样在Selenium测试页面中可以通过调取页面类来获取页面 ...
- miniFTP项目实战三
项目简介: 在Linux环境下用C语言开发的Vsftpd的简化版本,拥有部分Vsftpd功能和相同的FTP协议,系统的主要架构采用多进程模型,每当有一个新的客户连接到达,主进程就会派生出一个ftp服务 ...
- 第二百五十节,Bootstrap项目实战--响应式导航
Bootstrap项目实战--响应式导航 学习要点: 1.响应式导航 一.响应式导航 基本导航组件+响应式 第一步,声明导航区域,设置导航默认样式,设置导航条固定在顶部navbar样式class类,写 ...
- miniFTP项目实战五
项目简介: 在Linux环境下用C语言开发的Vsftpd的简化版本,拥有部分Vsftpd功能和相同的FTP协议,系统的主要架构采用多进程模型,每当有一个新的客户连接到达,主进程就会派生出一个ftp服务 ...
随机推荐
- java Map集合学习
学习语法还是从例子着手: FileDao fileDao=new FileBeanDaoImpl(); FileBean fileBean=new FileBean(); listBean=fileD ...
- colorbox在android上由于高度太高无法scroll问题
首先看问题截图: 我们可以看到弹出的colorbox页面的高度已经到了下面,你根本看不到"mistake cross"<=>"X". 我测试了iph ...
- 一句话为当前窗口客户区捉图: GetFormImage 来自万一的博客
一句话为当前窗口客户区捉图: GetFormImage http://www.cnblogs.com/del/archive/2008/10/24/1318738.html unit Unit1; i ...
- SQL Server 索引基本概念与优化
数据页和区 页 SQL Server 中的数据以“页”(Page)的形式保存数据,页是SQL Server 的IO单位,读/写一次至少是一页.一页为8K(8192byte). 页由三部分组成,页头,数 ...
- H2Database聚合函数
聚合函数(Aggregate Functions) AVG BOOL_AND BOOL_OR COUNT GROUP_CONCAT MAX MIN SUM SELECTIVITY ST ...
- Python - 更改pip源至国内镜像
永久使用 [windows] 在用户名目录下创建一个目录 C:\Users\xxx\pip [linux] ~/.pip/pip.conf 新建pip.ini [global] index-url = ...
- C#Winfrom Listview数据导入Excel
需引用 public void ExportToExecl() { System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog(); sf ...
- S11 day 95 RestFramework 之 视图
1. 基于APIVIEW视图序列化 我们会发现两个类有好多重复的代码.所以我们引入了GenericAPIView (继承了APIView) 2.Generic ApiVIew和 ListModel ...
- 201621123018《Java程序设计》第2周学习报告
Week02-Java基本语法与类库 1.本周学习总结 Java数据类型分为基本数据类型和引用数据类型.布尔型是Java特有的数据类型.本周重点学习了字符串类型String,String类型中==和e ...
- socket agent统一模板
# -*- coding: utf- -*- # data:-- : # user:DIY # file:agent_eay.py import socket def work(i): sock = ...