玩转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服务 ...
随机推荐
- [Zend Mail]发送中文名附件出现乱码解决方案
Zend Framework 1.0.* “=?UTF-8?B?”.base64_encode($title).“?=” 发送中文名附件,结果如图: 英文名附件,结果截图: 解决办法就是将中文文件名拼 ...
- 4张图看懂delphi 10生成ipa和在iPhone虚拟器上调试(教程)
4张图看懂delphi 10生成ipa和在iPhone虚拟器上调试(教程) (2016-02-01 03:21:06) 转载▼ 标签: delphi ios delphi10 教程 编程 分类: 编程 ...
- python的数据存储
Python存储数据 使用json.dump()和json.load() 不管专注的是什么,程序都把用户提供的信息存储在列表和字典等数据结构中.用户关闭程序时,你几乎总是要保存他们提供的信息:一种简单 ...
- SQL Server Extended Events 进阶 2:使用UI创建基本的事件会话
第一阶中我们描述了如何在Profiler中自定义一个Trace,并且让它运行在服务器端来创建一个Trace文件.然后我们通过Jonathan Kehayias的 sp_SQLskills_Conver ...
- LeetCode141:Linked List Cycle
题目: Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without usin ...
- json--pyton中obj与json的互转,js中obj与json的互转
json 解释:json是一种跨平台的通用的数据格式 python中对象(obj)与json之间的相互转换 1.对象(obj)转json格式的字符串 json.dumps(res) res = () ...
- electron-vue 开发环境搭建(Windows环境)
1.安装 Node.js,一切都基于这个.安装完成后,终端输入 node -v 验证. 2.建立自己的项目目录,然后进入目录. 安装 vue-cli ,终端输入 npm install -g vue- ...
- 使用Navicat 创建mysql存储过程,实现日期加流水号序列
目的:使用Navicat 创建mysql存储过程,实现格式为8位日期(年月日)+5位流水号序列. 步骤: 1.打开Navicat 登录数据库,点击导航栏上的函数,如下图: 2.点击新建函数,选择“过程 ...
- ACTIVEMQ主题、队列设置用户名密码
修改文件%ACTIVEMQ_BASE%/conf/activemq.xml,用户名密码储存在文件%ACTIVEMQ_BASE%/conf/credentials.properties中, active ...
- Jira API传字符串的换行问题 (文本编辑器使用)
因为jira的文本编辑器自动进行了2次转义,如果从API过来的文本换行需要手动处理.吐血. net里: desc = desc.Replace("\n", "\\n&qu ...