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. Python 3.x 的一些注意事项

    1. reload 被更改 需要 在console执行 from imp import reload 才能调用CT 同时,如果py文件是位于主文件夹深部的位置,可以这么做: import ComicT ...

  2. uoj#274. 【清华集训2016】温暖会指引我们前行(LCT)

    传送门 不难发现肯定是在温度的最大生成树上走是最优的 于是用\(LCT\)维护最大生成树,每一次加边时如果已经连通,就判断一下路径上的最小温度是否小于当前温度,是的话就断掉那条边,加入新边 //min ...

  3. 【渗透测试】如何使用burpsuite对特殊密码进行爆破

    爆破是渗透测试中必不可少的一部分,对于没有太大价值可利用的漏洞或是业务只有一个登陆页面时,爆破更是我们的最合适的选择.那么在爆破时,抛去目标系统对爆破频率的限制,如果遇到较为复杂的密码,该如何顺利进行 ...

  4. css-float浮动详细

    前言 pc端的页面为了保持良好的兼容性,一般会使用css2部分就支持的浮动(float)和定位(postion)来布局.浮动行为怪异,但有迹可循.以下下是在css揭秘一书中总结的浮动内幕. 包含块:浮 ...

  5. GraphicsLab Project之再谈Shadow Map

    作者:i_dovelemon 日期:2019-06-07 主题:Shadow Map(SM), Percentage Closer Filtering(PCF), Variance Shadow Ma ...

  6. 归档-对模型数组对象(存储到本地的plist文件)也数组里存放的是模型

    一.模型文件 (1)JLMainViewsModel.h文件 必须遵循 NSCoding协议 @interface JLMainViewsModel : NSObject<NSCopying,N ...

  7. 093 Restore IP Addresses 复原IP地址

    给定一个只包含数字的字符串,复原它并返回所有可能的IP地址格式.例如:给定 "25525511135",返回 ["255.255.11.135", " ...

  8. vuex 使用方法

    1.安装vuex扩展 : npm install vuex 2.在componets目录下新建 store.js 文件 import Vue from 'vue' import Vuex from ' ...

  9. Linux防火墙iptables配置开放某个端口

    开放某个端口 查看防火墙规则命令: iptables -L -n 添加端口 1.编辑iptables文件 vim /etc/sysconfig/iptables 2.添加开放端口配置 -A INPUT ...

  10. WPF之Binding【转】

    WPF之Binding[转] 看到WPF如此之炫,也想用用,可是一点也不会呀. 从需求谈起吧: 首先可能要做一个很炫的界面.见MaterialDesignInXAMLToolKit. 那,最主要的呢, ...