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.注意點
- 獲取Docment總數
// 如果沒有查詢條件,即查詢總量時,建議採用estimatedDocumentCount方法 // 如果有查詢條件, 只能通過countDocuments方法, 並且減以在查詢條件增加索引.
- Criteria的使用
不要再重新new Criteria對象,調用方式內存已經重新new對象了
- 聚合使用的問題
// 聚合對循序是有要求的 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) );
- 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);
- 更新$set和$serOnInsert
兩個操作不能出現同一個key
6.查詢條件操作符
指令 | 描述 |
---|---|
eq | 等於 |
lt | 小於 |
gt | 大於 |
gte | 大於等於 |
lte | 小於等於 |