MongoTemplate針對多條件查詢以及複雜查詢基本示例

針對mongotemplate的查詢寫法,可能會跟其他orm框架裏面的查詢寫法混淆,特地記錄一下.
一. 常用查詢:

  1. 查詢一條數據:(多用於保存時判斷db中是否已有當前數據,這裏 is 精確匹配,模糊匹配 使用 regex…)
public PageUrl getByUrl(String url) {  
        return findOne(new Query(Criteria.where("url").is(url)),PageUrl.class);  
    }  
  1. 查詢多條數據:linkUrl.id 屬於分級查詢
public List<PageUrl> getPageUrlsByUrl(int begin, int end,String linkUrlid) {          
        Query query = new Query();  
        query.addCriteria(Criteria.where("linkUrl.id").is(linkUrlid));  
        return find(query.limit(end - begin).skip(begin), PageUrl.class);          
    }  
  1. 模糊查詢:
public long getProcessLandLogsCount(List<Condition> conditions)  
    {  
        Query query = new Query();  
        if (conditions != null && conditions.size() > 0) {  
            for (Condition condition : conditions) {  
                query.addCriteria(Criteria.where(condition.getKey()).regex(".*?\\" +condition.getValue().toString()+ ".*"));  
            }  
        }  
        return count(query, ProcessLandLog.class);  
    }  

最下面,我在代碼親自實踐過的模糊查詢,只支持字段屬性是字符串的查詢,你要是查字段屬性是int的模糊查詢,還真沒轍。

  1. gte: 大於等於,lte小於等於…注意查詢的時候各個字段的類型要和mongodb中數據類型一致
public List<ProcessLandLog> getProcessLandLogs(int begin,int end,List<Condition> conditions,String orderField,Direction direction)  
    {  
        Query query = new Query();  
        if (conditions != null && conditions.size() > 0) {  
            for (Condition condition : conditions) {  
                if(condition.getKey().equals("time")){  
                    query.addCriteria(Criteria.where("time").gte(condition.getValue())); //gte: 大於等於  
                }else if(condition.getKey().equals("insertTime")){  
                    query.addCriteria(Criteria.where("insertTime").gte(condition.getValue()));  
                }else{  
                    query.addCriteria(Criteria.where(condition.getKey()).is(condition.getValue()));  
                }  
            }  
        }  
        return find(query.limit(end - begin).skip(begin).with(new Sort(new Sort.Order(direction, orderField))), ProcessLandLog.class);  
    }  

public List<DpsLand> getDpsLandsByTime(int begin, int end, Date beginDate,Date endDate) {  
  return find(new Query(Criteria.where("updateTime").gte(beginDate).lte(endDate)).limit(end - begin).skip(begin),  
    DpsLand.class);  
 }  

查詢字段不存在的數據

public List<GoodsDetail> getGoodsDetails2(int begin, int end) {  
        Query query = new Query();  
        query.addCriteria(Criteria.where("goodsSummary").not());  
        return find(query.limit(end - begin).skip(begin),GoodsDetail.class);  
    }  

查詢字段不爲空的數據

Criteria.where("key1").ne("").ne(null)  

查詢或語句:a || b

Criteria criteria = new Criteria();  
criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null));  

查詢且語句:a && b這裏寫代碼片
Criteria criteria = new Criteria();
criteria.and(“key1”).is(false);
criteria.and(“key2”).is(type);
Query query = new Query(criteria);
long totalCount = this.mongoTemplate.count(query, Xxx.class);

查詢一個屬性的子屬性,例如:查下面數據的key2.keyA的語句

 var s = {  
       key1: value1,  
       key2: {  
           keyA: valueA,  
           keyB: valueB  
       }  
   };  

@Query("{'key2.keyA':?0}")  
List<Asset> findAllBykeyA(String keyA);  
  1. 查詢數量:
public long getPageInfosCount(List<Condition> conditions) {  
        Query query = new Query();  
        if (conditions != null && conditions.size() > 0) {  
            for (Condition condition : conditions) {  
                query.addCriteria(Criteria.where(condition.getKey()).is(condition.getValue()));  
            }  
        }  
        return count(query, PageInfo.class);  
    }  
  1. 更新一條數據的一個字段:
public WriteResult updateTime(PageUrl pageUrl) {  
        String id = pageUrl.getId();  
        return updateFirst(new Query(Criteria.where("id").is(id)),Update.update("updateTime", pageUrl.getUpdateTime()), PageUrl.class);  
    }  
  1. 更新一條數據的多個字段:
//調用更新  
private void updateProcessLandLog(ProcessLandLog processLandLog,  
            int crawlResult) {  
        List<String> fields = new ArrayList<String>();  
        List<Object> values = new ArrayList<Object>();  
        fields.add("state");  
        fields.add("result");  
        fields.add("time");  
        values.add("1");  
        values.add(crawlResult);  
        values.add(Calendar.getInstance().getTime());  
        processLandLogReposity.updateProcessLandLog(processLandLog, fields,  
                values);  
    }  
//更新  
public void updateProcessLandLog(ProcessLandLog land, List<String> fields,List<Object> values) {  
        Update update = new Update();  
        int size = fields.size();  
        for(int i = 0 ; i < size; i++){  
            String field = fields.get(i);  
            Object value = values.get(i);  
            update.set(field, value);  
        }  
        updateFirst(new Query(Criteria.where("id").is(land.getId())), update,ProcessLandLog.class);  
    }  
  1. 刪除數據:
public void deleteObject(Class<T> clazz,String id) {  
        remove(new Query(Criteria.where("id").is(id)),clazz);  
    }  

9.保存數據:

//插入一條數據  
public void saveObject(Object obj) {  
        insert(obj);  
    }  

//插入多條數據      
public void saveObjects(List<T> objects) {  
        for(T t:objects){  
            insert(t);  
        }  
    }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章