使用mongotemplate 操作Mongo笔记

1.查询 Filters

  • 获取collection
    MongoCollection<Document> collection = mongoTemplate.getCollection(DATA_COLLECTION);
    
  • Bson条件查询 (用法存在问题)
    Bson filter = Filters.eq(LedConstants.MONGODB_CONTROLLER_ID, controllerId);
    
    if (collectType != null) {
    
        filter = Filters.and(filter, Filters.eq(LedConstants.MONGODB_COLLECT_TYPE, collectType));
    }
    if (startDate != null) {
    
        filter = Filters.and(filter, Filters.gte(LedConstants.MONGODB_CREATE_DATE, startDate));
    
    }
    Bson orderBy = Sorts.ascending("alarmCode");
    FindIterable<Document> it =  mongoTemplate.getCollection("dataCollection").find(filter).sort(new BasicDBObject("createDate", -1)).skip(Constants.INT_VALUE0).limit(Constants.INT_VALUE1);
    
    MongoCursor<Document> cursor = it.iterator();
    
    Document document = null;
    
    while (cursor.hasNext()) {
        document = cursor.next();
    }
    
    • Bson条件查询
    List<Bson> filter = new ArrayList<>();
    if (ccodeList != null && !ccodeList.isEmpty()) {
        filter.add(Filters.in(LedConstants.MONGODB_CONTROLLER_CODE, ccodeList));
    }
    
    if (extensiontype != null) {
        filter.add(Filters.eq(LedConstants.MONGODB_EXTENSION_TYPE, extensiontype));
    }
    
    if (start_d != null && end_d != null) {
        filter.add(Filters.and(Filters.gte(LedConstants.MONGODB_UPDATE_DATE, start_d), Filters.lte(LedConstants.MONGODB_UPDATE_DATE, end_d)));
    }
    Bson orderBy = Sorts.ascending(LedConstants.MONGODB_CONTROLLER_CODE, LedConstants.MONGODB_CONTROLLER_EXTID, LedConstants.MONGODB_READDATE);
    
    FindIterable<Document> it = collection.find(Filters.and(filter)).sort(orderBy);
    
    MongoCursor<Document> cursor = it.iterator();
    
    Document document = null;
    
    while (cursor.hasNext()) {
        document = cursor.next();
    }
    
  • 聚合查询表 Aggregates
    // 一
    Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.project("_id","goodsName","totalPrice").andExpression("price * pcs").as("totalPrice"),
                    Aggregation.group("goodsName").sum("totalPrice").as("totalPrice")
            );
    AggregationResults<GoodsAggDto> refreshTask = mongoTemplate.aggregate(aggregation, "order", GoodsAggDto.class);
    
    // 二
    List<AggregationOperation> operations = new ArrayList<>();
    
    operations.add(Aggregation.project("controllerId","controllerCode","collectType","collectValue","createDate"));
    operations.add(Aggregation.match(Criteria.where("controllerCode").is(code)));
    
    //  sortCond
    operations.add(Aggregation.sort(Sort.Direction.ASC, LedConstants.MONGODB_CREATE_DATE));
    
    operations.add(Aggregation.group("controllerCode", "controllerId", "collectType")
            .last("collectValue").as("collectValue")
            .last("collectType").as("collectType")
            .last("createDate").as("createDate")
    );
    
    

2.插入

  • 插入一条数据
    Document document = new Document();
    document.put(LedConstants.MONGODB_CONTROLLER_ID, c.getCid());
    document.put(LedConstants.MONGODB_CONTROLLER_CODE, c.getCcode());
    
    document.put(LedConstants.MONGODB_CREATE_DATE, Calendar.getInstance().getTime());
    document.put(LedConstants.MONGODB_COLLECT_TYPE, collectType);
    document.put(LedConstants.MONGODB_COLLECT_VALUE, collectValue);
    collection.insertOne(document);
    
  • 插入多条数据
    List<Document> list = new ArrayList<>();
        for(Controller c: clist){
            Document document = new Document();
            document.put(LedConstants.MONGODB_CONTROLLER_ID, c.getCid());
            document.put(LedConstants.MONGODB_CONTROLLER_CODE, c.getCcode());
            document.put(LedConstants.MONGODB_ALARM_CODE, alarmCode);
            document.put(LedConstants.MONGODB_ALARM_MSG, LedConfig.getProperty(alarmCode) + "_" + alarmMsgPlus);
            document.put(LedConstants.MONGODB_ALARM_STATE, LedConstants.MONGODB_ALARM_STATE_NEW);
            document.put(LedConstants.MONGODB_ALARM_SEVERITY, severity);
            document.put(LedConstants.MONGODB_CREATE_DATE, Calendar.getInstance().getTime());
            document.put(LedConstants.MONGODB_ALARM_COUNT, Constants.INT_VALUE0);
            list.add(document);
        }
    mongoTemplate.getCollection(ALARM_COLLECTION).insertMany(list);
    

3.更新 updates

  • set/upsert

    Criteria criteria = Criteria.where(LedConstants.MONGODB_CONTROLLER_ID).is(c.getCid())
                    .and(LedConstants.MONGODB_ALARM_CODE).is(LedConstants.MONGODB_ALARM_STATE_NEW)
                    .and(LedConstants.MONGODB_ALARM_STATE).is( LedConstants.MONGODB_ALARM_STATE_NEW)
                    .and(LedConstants.MONGODB_USER_ID).is(userId);
    Query query = new Query();
    query.addCriteria(criteria);
    
    // 更新内容
    Update update = Update.update(LedConstants.MONGODB_ALARM_STATE,  LedConstants.MONGODB_ALARM_STATE_AUTO);
    
    UpdateResult result = mongoTemplate.upsert(query, update, ALARM_COLLECTION);
    System.out.println("受影响的行数================>" + result.getModifiedCount());
    
  • set/setOnInsert/upsert query作为查询条件,插入查到,则更新set中的值,如果未查到,则把query中的值和setOnInsert的值一起插入

    Criteria criteria = Criteria.where(LedConstants.MONGODB_CONTROLLER_ID).is(c.getCid())
                    .and(LedConstants.MONGODB_ALARM_CODE).is(LedConstants.MONGODB_ALARM_STATE_NEW)
                    .and(LedConstants.MONGODB_ALARM_STATE).is( LedConstants.MONGODB_ALARM_STATE_NEW)
                    .and(LedConstants.MONGODB_USER_ID).is(userId);
    Query query = new Query();
    query.addCriteria(criteria);
    
    Update update = Update.update("updateDate",  date);
    update.set("collectValue",  100);
    update.setOnInsert("crateDate", date);
    

4.删除

Criteria criteria = Criteria.where(LedConstants.MONGODB_ALARM_STATE)
                .nin(new int[] { LedConstants.MONGODB_ALARM_STATE_NEW });
Query query = new Query();
query.addCriteria(criteria);
mongoTemplate.remove(query, ALARM_COLLECTION);

5.注意点

  1. 获取Docment总数
    
        // 如果没有查询条件,即查询总量时,建议采用estimatedDocumentCount方法
        // 如果有查询条件, 只能通过countDocuments方法, 并且减以在查询条件增加索引.
    
  2. Criteria的使用
    
        不要再重新new Criteria对象,调用方式内存已经重新new对象了  
    
  3. 聚合使用的问题
    
        // 聚合对循序是有要求的  match  sort group
        Map<String, MongoDataDto> dtoMap = new HashMap<>();
    	List<AggregationOperation> operations = new ArrayList<>();
    
    	//  matchCond
    	Criteria criteria = Criteria.where(LedConstants.MONGODB_CONTROLLER_CODE).is(controller.getCcode());
    
    	if (pollingLastTime != null) {
    		criteria.and(LedConstants.MONGODB_CREATE_DATE).gte(pollingLastTime);
    	}
    	operations.add(Aggregation.match(criteria));
    
    	Sort sort = new Sort(Sort.Direction.ASC,  LedConstants.MONGODB_CREATE_DATE);
    
    	operations.add(Aggregation.sort(sort));
    
    	operations.add(Aggregation.group(LedConstants.MONGODB_CONTROLLER_CODE, LedConstants.MONGODB_CONTROLLER_ID,
            LedConstants.MONGODB_COLLECT_TYPE, LedConstants.MONGODB_CONTROLLER_EXTID
            )
            .last(LedConstants.MONGODB_COLLECT_VALUE).as(LedConstants.MONGODB_COLLECT_VALUE)
            .last(LedConstants.MONGODB_CREATE_DATE).as(LedConstants.MONGODB_CREATE_DATE)
    	);
    
  4. Criteria and 和 andOperator 区别
        // andOperator里面查询的是同一个字段多个约束的问题
        criteria.andOperator(Criteria.where(LedConstants.MONGODB_CREATE_DATE).gte(startDate),
    	    Criteria.where(LedConstants.MONGODB_CREATE_DATE).lte(endDate));
        // and 用于不同字段
        criteria.and("extid").is(extid);
    
  5. 更新$set和$serOnInsert
      两个操作不能出现同一个key
    

6.查询条件操作符

指令 描述
eq 等于
lt 小于
gt 大于
gte 大于等于
lte 小于等于
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章