MongoDB基于Morphia (二)demo 包含聚合汇总 多条件查询

MongoDB基础语句

注:新增字段 也是用其中的set 但是确保实体类中有新增的属性(使用morphia)

例如::
books是表名 “book_serial_num” : “B1013687616857538560” 为筛选条件
mongo中语句
新增字段 如果原来有这个字段就是更新
db.getCollection(‘books’).update({“book_serial_num” : “B1013687616857538560”},{"$set" : {“test2”:“33”}})

查找
db.getCollection(‘books’).find({“book_serial_num” : “B1013687616857538560”})

删除:删除test2的字段 后面必须为“”
db.getCollection(‘books’).update({“book_serial_num” : “B1013687616857538560”},{"$unset" : {“test2”:""}})

详细方法demo
更新操作:

 @Override
    public void updateTitle(String book_serial_num, String main_title) {
        FieldFilter filter = new FieldFilter(MonthlyPaymentActivityBooks.BOOK_SERIAL_NUM, FilterOp.EQ, book_serial_num);
        FieldFilter[] params = new FieldFilter[]{filter};
        Query query = this.getDao().createQuery();
        for (FieldFilter filter1: params) {
            query.filter(filter1.getField()+filter1.getOperator().getOperator(),filter1.getValue());
        }
        UpdateOperations ops = this.getDao().getDs().createUpdateOperations(MonthlyPaymentActivityBooks.class).set(MonthlyPaymentActivityBooks.MAIN_TITLE, main_title);

        getDao().update(query,ops);
    }

聚合汇总操作
方式一

/**
其中paramMap 为 条件    codes为要汇总的字段名
*/
 @Override
    public Map> getTotalBy(Map paramMap, String... codes) {

        StringBuffer map = new StringBuffer();
        map.append("function() {");
        map.append("  var value ={");
        for(int i=0;i0){
                map.append(",");
            }
            map.append(codes[i]).append(":this.").append(codes[i]);

        }
        map.append("};");
        map.append("emit(this.book_serial_num,value); ");
        map.append("}");

        StringBuffer reduce = new StringBuffer();
        reduce.append("function(key,values) {");
        reduce.append("  var result ={");
        for(int i=0;i0){
                reduce.append(",");
            }
            reduce.append(codes[i]).append(":0");

        }

        reduce.append("};");
        reduce.append("for(var i=0;i> bookMap = new HashMap<>();
        //遍历获得总值
        while (dbCursor.hasNext()) {
            DBObject resultObj = dbCursor.next();
            String bookId = (String)resultObj.get("_id");
            LinkedHashMap param = new LinkedHashMap<>();
            for(String code:codes){
                DBObject data = (DBObject)resultObj.get("value");
                if(null!=data.get(code) && !data.get(code).toString().contains("bson")) {
                    if (param.get(code) != null) {
                        param.put(code, param.get(code) + Double.valueOf(String.valueOf(data.get(code))));
                    } else {
                        param.put(code, Double.valueOf(String.valueOf(data.get(code))));
                    }
                }
            }
            bookMap.put(bookId,param);
        }


       return bookMap;
    }

方式二::

 /**
     * 汇总查询  可使用  同上个方法
     * @param paramMap  查询条件
     * @param code      统计的字段
     */
    @Override
    public void getTotalByGroup(Map paramMap, String[] code) {
        Query query = dao.createQuery();

        Long start_time = (Long) paramMap.get("start_time");
        Long end_time = (Long) paramMap.get("end_time");
        String channelCode = (String) paramMap.get("channelCode");

        List params = new ArrayList<>();
        params.add(new FieldFilter(ClickRecentReport.REPORT_TIME, FilterOp.GTE,start_time));
        params.add(new FieldFilter(ClickRecentReport.REPORT_TIME,FilterOp.LTE,end_time));
        params.add(new FieldFilter(ClickRecentReport.CHANNEL_CODE,FilterOp.EQ,channelCode));


        for (FieldFilter filter : params) {
            query.filter(filter.getField() + filter.getOperator().getOperator(), filter.getValue());
        }

        AggregationPipeline aggregationPipeline = dao.getDs().createAggregation(ClickRecentReport.class);

//        String[] code = new String[]{"uv","click","click_total","pv"};
        aggregationPipeline.
                match(query).
                group(
                        id(grouping("channel_code"), grouping("book_serial_num")),
                        grouping("uv", sum("uv")),
                        grouping("click", sum("click")),

                        grouping("click_total", sum("click_total")),
                        grouping("pv", sum("pv"))

                );
//ClickRecentReportCopy和ClickRecentReport相同字段 但必须进行此操作
        Iterator iterator = aggregationPipeline.aggregate(ClickRecentReportCopy.class);
        System.out.println(iterator.hasNext());
        while (iterator.hasNext()) {
            ClickRecentReportCopy ug = iterator.next();
            System.out.println(ug);
        }
    }

新增 汇总方式三: 基于mapreduce

@Override
    public List getCount(Long startTime, Long endTime, String channelCode) {
		//根据CHANNEL_CODE汇总
        BasicDBObject key = new BasicDBObject();
        key.put(BookCollectionAnalyse.CHANNEL_CODE, 1);
        //条件  加入条件
        BasicDBObject cond = new BasicDBObject();
        BasicDBObject queryObj = new BasicDBObject();
        queryObj.append("$gte", startTime);
        queryObj.append("$lte", endTime);
        cond.put(BookPUVAnalyse.REPORT_TIME, queryObj);
        if (StringUtils.isNotBlank(channelCode)) {
            BasicDBObject queryObj2 = new BasicDBObject();
            queryObj2.append("$eq", channelCode);
            cond.put(BookCollectionAnalyse.CHANNEL_CODE, queryObj2);
        }

        BasicDBObject initial = new BasicDBObject();
        initial.append("collection_count", 0);
        //reduce   汇总内容
        StringBuffer reduce = new StringBuffer();
        reduce.append("function Reduce(doc, out) {");
        reduce.append("out.collection_count+=doc.collection_count;");
        reduce.append("out.channel_name=doc.channel_name;");
        reduce.append("out.channel_code=doc.channel_code;");
        reduce.append("}");

        BasicDBList groupList = (BasicDBList) getDao().getCollection().group(key, cond, initial, reduce.toString());
        List result = new ArrayList<>();
        //汇总数据 保存到实体中
        if (groupList != null && groupList.size() > 0) {
            for (int i = 0; i < groupList.size(); i++) {
                BasicDBObject obj = (BasicDBObject) groupList.get(i);
                BookCollectionAnalyse bookCollectionAnalyse = new BookCollectionAnalyse();
                bookCollectionAnalyse.setCollection_count(obj.getLong(BookCollectionAnalyse.COLLECTION_COUNT));
                bookCollectionAnalyse.setChannel_code(obj.getString(BookCollectionAnalyse.CHANNEL_CODE));
                bookCollectionAnalyse.setChannel_name(obj.getString(BookCollectionAnalyse.CHANNEL_NAME));
                result.add(bookCollectionAnalyse);
            }
        }
        return result;
    }

多条件或 和 并 查询

/**
	vagueParams中为或的条件   params为并且的条件
*/
public PageList findByPage(List params, PageBounds ageBounds, List vagueParams) {
        Query query = getDao().createQuery();
        for (FieldFilter filter : params) {
            Object value = filter.getValue();
            if (null == value) {
                continue;
            }
            if (value instanceof String && StringUtils.isEmpty(((String) value))) {
                continue;
            }
            query.filter(filter.getField() + filter.getOperator().getOperator(), value);
        }

        if (vagueParams != null) {
            Criteria[] arry = new Criteria[vagueParams.size()];
            int index = 0;
            for (FieldFilter filter : vagueParams) {
                Object value = filter.getValue();
                arry[index] = query.criteria(filter.getField()).contains(value.toString());
                index++;
            }
            query.or(arry);
        }


        List orderBys = ageBounds.getOrders();
        String orderby = StringUtils.EMPTY;
        for (Order order : orderBys) {
            String dir = (order.getDirection() == Order.Direction.ASC) ? StringUtils.EMPTY : SeparatorConstant.HYPHEN;
            if (StringUtils.isNotBlank(orderby)) {
                orderby += ",";
            }
            orderby += dir + order.getProperty();
        }
        if (StringUtils.isNotBlank(orderby)) {
            query.order(orderby);
        }
        query.offset(ageBounds.getOffset());
        query.limit(ageBounds.getLimit());
        List findList = getDao().find(query).asList();
        //分页
        int totalCount = (int) query.countAll();
        PageList list = new PageList<>();
        Pagination pagination = new Pagination(ageBounds.getPage(), ageBounds.getLimit(), totalCount);
        list.setPagination(pagination);
        list.addAll(findList);
        return list;
    }

你可能感兴趣的:(mongo)