package com.jttx.demo;
 
import com.mongodb.*;
import com.mongodb.util.JSON;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
 
 
/**
 * Created by superman on 2014/6/30.
 */
 
public class MongoManager {
    private DB db;
    private static final Integer soTimeOut = 300000;
    private static final Integer connectionsPerHost = 500;
    private static final Integer threadsAllowedToBlockForConnectionMultiplier = 500;
 
    public MongoManager(String host, int port, String database) {
        try {
            MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), new MongoClientOptions.Builder()
                    .socketTimeout(soTimeOut)
                    .connectionsPerHost(connectionsPerHost)
                    .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier)
                    .socketKeepAlive(true)
                    .build()
            );
            db = mongoClient.getDB(database);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
 
    public void save(String collection, DBObject dbObject) {
        db.getCollection(collection).save(dbObject);
    }
 
    public void delete(String collection, DBObject query) {
        db.getCollection(collection).remove(query);
    }
 
    // 此处不使用toArray()方法直接转换为List,是因为toArray()会把结果集直接存放在内存中,
    // 如果查询的结果集很大,并且在查询过程中某一条记录被修改了,就不能够反应到结果集中,从而造成"不可重复读"
    // 而游标是惰性获取数据
    public List<DBObject> find(String collection, DBObject query, DBObject fields, int limit) {
        List<DBObject> list = new LinkedList<>();
        Cursor cursor = db.getCollection(collection).find(query, fields).limit(limit);
        while (cursor.hasNext()) {
            list.add(cursor.next());
        }
        return list.size() > 0 ? list : null;
    }
 
    public List<DBObject> find(String collection, DBObject query, DBObject fields, DBObject orderBy, int pageNum, int pageSize) {
        List<DBObject> list = new ArrayList<>();
        Cursor cursor = db.getCollection(collection).find(query, fields).skip((pageNum - 1) * pageSize).limit(pageSize).sort(orderBy);
        while (cursor.hasNext()) {
            list.add(cursor.next());
        }
        return list.size() > 0 ? list : null;
    }
 
    public DBObject findOne(String collection, DBObject query, DBObject fields) {
        return db.getCollection(collection).findOne(query, fields);
    }
 
    public void update(String collection, DBObject query, DBObject update, boolean upsert, boolean multi) {
        db.getCollection(collection).update(query, update, upsert, multi);
    }
 
    public long count(String collection, DBObject query) {
        return db.getCollection(collection).count(query);
    }
 
 
    //查询出key字段,去除重复,返回值是{_id:value}形式的list
    public List distinct(String collection, String key, DBObject query) {
        return db.getCollection(collection).distinct(key, query);
    }
 
    //适用于小数据量查询
    public void distinctWithHandle(String collection, String key, DBObject query, CursorHandle cursorHandle) {
        List<DBObject> pipeLine = new ArrayList<>();
        pipeLine.add(new BasicDBObject("$match", query));
        String groupStr = String.format("{$group:{_id:'$%s'}}", key);
        pipeLine.add((DBObject) JSON.parse(groupStr));
        Cursor cursor = db.getCollection(collection).aggregate(pipeLine, AggregationOptions.builder().build());
        cursorHandle.handle(cursor);
    }
 
    //适用于大数据量查询
    public void distinctWithHandle(String collection, String key, DBObject query, int pageNo, int pageSize, CursorHandle cursorHandle) {
        List<DBObject> pipeLine = new ArrayList<>();
        pipeLine.add(new BasicDBObject("$match", query));
        String groupStr = String.format("{$group:{_id:'$%s'}}", key);
        pipeLine.add((DBObject) JSON.parse(groupStr));
        pipeLine.add(new BasicDBObject("$skip", (pageNo - 1) * pageSize));
        pipeLine.add(new BasicDBObject("$limit", pageSize));
        Cursor cursor = db.getCollection(collection).aggregate(pipeLine, AggregationOptions.builder().build());
        cursorHandle.handle(cursor);
    }
 
 
}

2. [代码]CursorHandle

1
2
3
4
5
6
7
8
9
10
11
package com.jttx.demo;
 
 
import com.mongodb.Cursor;
 
/**
 * Created by superman on 2014/9/15.
 */
public interface CursorHandle {
    public void handle(Cursor cursor);
}

java mongodb 增删改查 工具类的更多相关文章

  1. springMVC操作mongoDB增删改查

    下面是mongoDb简单的增删改查(新闻类) 附:query.addCriteria(Criteria.where("modelId").ne("").ne(n ...

  2. 数据库——MongoDB增删改查

    MongoDB增删改查操作 本文包含对数据库.集合以及文档的基本增删改查操作 数据库操作 #1.增 use config #如果数据库不存在,则创建并切换到该数据库,存在则直接切换到指定数据库. #2 ...

  3. MongoDB - 增删改查及聚合操作

    目录 MongoDB - 增删改查及聚合操作 一. 数据库操作(database) 1. 创建及查看库 2. 删除库 二. 集合collectionc=操作(相当于SQL数据库中的表table) 1. ...

  4. MongoDB(六)java操作mongodb增删改查

    java操作mysql数据库的代码我们已经了如指掌了.增删改查,java对mongodb数据库也是类似的操作,先是数据库连接.再是进行操作. 首先我们进入进入admin数据库.然后建立自己的数据库te ...

  5. 第二部分 Mongodb增删改查

    学习内容:1.mongodb增加操作2.mongodb删除操作3.mongodb查询操作增删改查的高级应用Capped Collection(固定集合)GridFS 大文件上传或下载 1: inser ...

  6. JAVA JDBC 增删改查简单例子

    1.数据库配置文件jdbc.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username= ...

  7. [MongoDB]增删改查

    摘要 上篇文章学习了mongodb在windows上的安装,以及如何开启mongodb,最后列举了简单的增删改查操作.本篇将继续深入学习一下增删改查. 相关文章 [MongoDB]入门操作 CRUD ...

  8. MongoDB增删改查表文档

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...

  9. mongodb增删改查操作

    Note:mongodb存储的是文档,且文档是json格式的对象,所以增删改查都必须是json格式对象. 注:mongodb常用库和表操作,但mongodb在插入数据时,不需要先创建表. show d ...

随机推荐

  1. 洛谷P4884 多少个1?(BSGS)

    传送门 模数好大……__int128好麻烦……而且BSGS第一次写有点写蒙了…… $11...1(N个1)\equiv k(mod m)$很难算,那么考虑转化一下 先把$11...1(N个1)$写成$ ...

  2. SpringMvc源码入门

    servlet httpServletRequest httpServlet

  3. Sublime Text 报“Pylinter could not automatically determined the path to lint.py

    Pylinter could not automatically determined the path to lint.py. please provide one in the settings ...

  4. css-原理详解

    语法 CSS 规则由两个主要的部分构成:选择器,以及一条或多条声明: 选择器一般使用id或者class选择器,声明由{}包含,每条声明由一个属性和一个值组成. .city { float:left; ...

  5. Ubuntu使用实录

    在实验室的电脑上重新配置了Linux开发环境,使用的是Ubuntu 14.04.5 LTS. 在开发中遇到的问题甚多,一一记录如下: 1.切换为root身份 先给root用户设定密码,然后进行切换 s ...

  6. 线段树-区间更新-HDU 1689

    #include <iostream> #include <cstdio> #include <string> #include <cstring> # ...

  7. 如何使用LESS 深度定制Bootstrap

    一.LESS是什么? Less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量.Mixin.函数等特性,使 CSS 更易维护和扩展. 中文介绍:http://lesscss.cn/ 有 ...

  8. HTML超链接的使用

    基本语法 <a href="" target="打开方式" name="页面锚点名称">链接文字或图片</a> 属性 ...

  9. [未读]angularjs权威教程

    正在啃,赶脚不错...

  10. 初始Mybatis,好累,自己感觉自己快坚持不了了

    Mybatis1.持久化 持久化,就是内存数据和硬盘数据状态的转换 2.ORM思想Object Relation Mapping 对象关系映射 3.MyBatis入门案例 3.1导入jar包 依赖 & ...