MongoDB增删查改

一、MongoDB与MySQL对比

MySQL关系数据库由数据库(database)、表(table)、记录(record)三个层次概念组成,

MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。

MongoDB的集合对应关系型数据库里的表,但是集合中没有列、行的概念,这体现了模式自由的特点。

二、MongoDB命令行

1、数据库的增删改查

增:
use db1        :#有则切换,无则新 增
查:
show dbs        #查看所有数据库
db                 #查看当前库—下面db.xx中db是命令,不是数据库名
删:
db.dropDatabase()
注:刚新建的数据库, show dbs时并不会显示,只有插入数据啦,才会显示。

2、集合(表)的增删改

增:
db.user #user表
与数据库创建同理,当第一个文档插入时,集合就会被创建

默认创建collection表名(集合):db.collection.insert({age:1})

创建person表:db.person.insert({'a':1})

查:
show collections查询当前库所有集合
show tables #这两个是一样的
#只要是空不显示


删:
db.user.info.help() #查看帮助
db.user.info.drop()

改:

修改表名:db.旧表名.renameCollection("新表名")

3、文档(记录)的增删改

三、MongoDB增删查改

1、求和

    private BigDecimal getBetAmount(final Criteria criteria) {
        Aggregation totalBetAmountAggregation = Aggregation.newAggregation(
                Aggregation.match(criteria), Aggregation.group(OrderRecordPO.Fields.id)
                        .sum(OrderRecordPO.Fields.betAmount).as("betAmount"),
                Aggregation.project("betAmount"));
        AggregationResults sumAmountAggregate = mongoTemplate.aggregate(totalBetAmountAggregation,
                OrderRecordPO.COLLECTION_NAME, OrderPageVO.class);
        BigDecimal totalBetAmount = sumAmountAggregate.getMappedResults().size() > 0 ?
                sumAmountAggregate.getMappedResults().get(0).getBetAmount() : BigDecimal.ZERO;
        return totalBetAmount;
    }

2、分页

            Criteria criteria = new Criteria();
            criteria.and(OrderRecordPO.Fields.orderId).in(vo.getOrderList());
            long count = mongoTemplate.count(Query.query(criteria), OrderRecordPO.COLLECTION_NAME);
            Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(criteria),
                    Aggregation.project().and(OrderRecordPO.Fields.venueCode).as("venueCode")
                            .and(OrderRecordPO.Fields.gameCode).as("gameCode")
                            .and(OrderRecordPO.Fields.vipRankCode).as("vipRankCode")
                            .and(OrderRecordPO.Fields.validAmount).as("validBetAmount")
                            .and(OrderRecordPO.Fields.rebateRate).as("rebateRate")
                            .and(OrderRecordPO.Fields.venueName).as("venueName")
                            .and(OrderRecordPO.Fields.gameName).as("gameName")
                            .and(OrderRecordPO.Fields.rebateAmount).as("rebateAmount"),
                    Aggregation.skip((vo.getPageNumber() - 1) * vo.getPageSize()),
                    Aggregation.limit(vo.getPageSize())
            ).withOptions(new AggregationOptions.Builder().allowDiskUse(true).build());
            AggregationResults aggregate = mongoTemplate.aggregate(aggregation,
                    OrderRecordPO.COLLECTION_NAME, UserRebatePageVO.class);
            List result = aggregate.getMappedResults();
            Page rebateVOPage = new Page<>(vo.getPageNumber(), vo.getPageSize(), count);
            rebateVOPage.setRecords(result);

3、排序

    public GetLastOrderRecordVO getLastOrderRecord(String userAccount) {
        Query query = new Query();
        query.addCriteria(Criteria.where(OrderRecordPO.Fields.userAccount).is(userAccount));
        // 根据投注时间降序
        Sort.Direction direction = Sort.Direction.DESC;
        Sort sort = Sort.by(direction, OrderRecordPO.Fields.betTime);
        query = query.with(sort);
        return mongoTemplate.findOne(query, GetLastOrderRecordVO.class, OrderRecordPO.COLLECTION_NAME);
    }

4、求总数

    private int getCastPersonCount(Criteria criteria) {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group(OrderRecordPO.Fields.userAccount)
                        .count().as("castPersonCount"),
                Aggregation.project()
                        .and("castPersonCount").as("castPersonCount")
        ).withOptions(new AggregationOptions.Builder().allowDiskUse(true).build());
        AggregationResults aggregate = mongoTemplate.aggregate(
                        aggregation, OrderRecordPO.COLLECTION_NAME, HashMap.class);
        List list = aggregate.getMappedResults();
        if(list==null || list.isEmpty()){
            return 0;
        }
        return list.size();
    }

1、MongoDB的聚合函数

public List findUserBackWaterOrders(final OrderVO orderVO) {
        Criteria criteria = new Criteria();
        criteria.and(OrderDTO.Fields.betTime)
                .gte(orderVO.getBetBeginTime())
                .lte(orderVO.getBetEndTime());
        
    criteria.and(OrderDTO.Fields.userType).is(UserTypeEnum.FORMAL_PLAY.getCode());

        Criteria criteria1 = new Criteria();
        criteria1.and(OrderDTO.Fields.agentId).in(orderVO.getAgentIds());

        Criteria criteria2 = new Criteria();
        criteria2.and(OrderDTO.Fields.merchantId).is(orderVO.getMerchantId())
                 .and(OrderDTO.Fields.agentId).isNull();


        criteria.orOperator(criteria1, criteria2);


        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group(OrderDTO.Fields.userId)
                        .sum(OrderDTO.Fields.validAmount)
                        .as("validAmount")
                        .first(OrderDTO.Fields.merchantId).as("merchantId")
                        .first(OrderDTO.Fields.agentId).as("agentId")
                        .first(OrderDTO.Fields.userId).as("userId")
                        .first(OrderDTO.Fields.userBelong).as("userBelong"),
                // 显示字段过滤
                Aggregation.project()
                        .and(OrderDTO.Fields.userId).as("userId")
                        .and(OrderDTO.Fields.merchantId).as("merchantId")
                        .and(OrderDTO.Fields.agentId).as("agentId")
                        .and(OrderDTO.Fields.validAmount).as("validAmount")
                        .and(OrderDTO.Fields.userBelong).as("userBelong")
        ).withOptions(new AggregationOptions.Builder().allowDiskUse(true).build());

        AggregationResults aggregate = mongoTemplate.aggregate(aggregation,"order", OrderVO.class);

        return aggregate.getMappedResults();
    }

你可能感兴趣的:(mongodb,数据库)