前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >玩转mongodb(三):mongodb项目实战(初战)

玩转mongodb(三):mongodb项目实战(初战)

作者头像
壮壮熊
修改2023-01-17 14:57:10
5460
修改2023-01-17 14:57:10
举报
文章被收录于专栏:程序猿牧场程序猿牧场

说明:

代码语言:txt
复制
    主要功能:对mongoDB的集合做增删改查。
代码语言:txt
复制
    项目的运行环境:tomcat6、jdk8。
代码语言:txt
复制
    所用技术:mongoDB、jsp/servlet、前端bootstrap。

mongoDB工具类:

代码语言:txt
复制
    定义一个MongoDBUtil的枚举类,枚举类中定义一个instance实例。
代码语言:txt
复制
    MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够。
代码语言:txt
复制
    注意Mongo已经实现了连接池,并且是线程安全的。
代码语言:txt
复制
    设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可。
代码语言:txt
复制
    Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,DB和DBCollection是绝对线程安全的。
代码语言:javascript
复制
public enum MongoDBUtil {
    /**
     * 定义一个枚举的元素,它代表此类的一个实例
     */
    instance;
}
代码语言:txt
复制
    在MongoDBUtil类中,定义一个MongoClient对象,并根据IP和端口获得该对象。
代码语言:javascript
复制
private MongoClient mongoClient;
static {
    System.out.println("===MongoDBUtil初始化===");
    // 从配置文件中获取属性值
    String ip = "localhost";
    int port = 27017;
    instance.mongoClient = new MongoClient(ip, port);
}
代码语言:txt
复制
    根据MongoClient对象,得到MongoDataBase对象和MongoConnection<Document>对象。
代码语言:javascript
复制
/**
     * 获取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;
    }
代码语言:txt
复制
    工具类的查询、插入、更新、删除方法。
代码语言:javascript
复制
/**条件查询*/
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})

代码语言:txt
复制
    插入功能的servlet
代码语言:javascript
复制
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!");
代码语言:txt
复制
    插入功能的jsp
代码语言:javascript
复制
<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>

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

代码语言:txt
复制
    更新功能的servlet
代码语言:javascript
复制
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!");
代码语言:txt
复制
    更新功能的jsp
代码语言:javascript
复制
<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>

删除:对应MongoDB中脚本的db.getCollection('person').remove({"name":"ryan1"})

代码语言:txt
复制
    删除功能的servlet
代码语言:javascript
复制
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!");
代码语言:txt
复制
    删除功能的jsp
代码语言:javascript
复制
<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>
代码语言:txt
复制
    **查找**:对应MongoDB中脚本的db.getCollection('person').find({})
代码语言:txt
复制
    查找功能的servlet
代码语言:javascript
复制
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));
代码语言:txt
复制
    查找功能的jsp
代码语言:javascript
复制
<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>
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-01-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序猿牧场 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档