本篇文章為大家展示了怎么在java項目中利用MongoDB進(jìn)行查詢操作,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)建站-云計算及IDC服務(wù)提供商,涵蓋公有云、IDC機房租用、托管服務(wù)器、等保安全、私有云建設(shè)等企業(yè)級互聯(lián)網(wǎng)基礎(chǔ)服務(wù),聯(lián)系電話:028-86922220
java 中mongodb的各種操作查詢的實例詳解
一. 常用查詢:
1. 查詢一條數(shù)據(jù):(多用于保存時判斷db中是否已有當(dāng)前數(shù)據(jù),這里 is 精確匹配,模糊匹配 使用regex...)
public PageUrl getByUrl(String url) { return findOne(new Query(Criteria.where("url").is(url)),PageUrl.class); }
2. 查詢多條數(shù)據(jù):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); }
3.模糊查詢:-----關(guān)鍵字---regex
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的模糊查詢,還真沒轍。
4.gte: 大于等于,lte小于等于...注意查詢的時候各個字段的類型要和mongodb中數(shù)據(jù)類型一致
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); }
查詢字段不存在的數(shù)據(jù) -----關(guān)鍵字---not
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); }
查詢字段不為空的數(shù)據(jù) -----關(guān)鍵字---ne
Criteria.where("key1").ne("").ne(null)
查詢或語句:a || b ----- 關(guān)鍵字---orOperator
Criteria criteria = new Criteria(); criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null));
查詢且語句:a && b ----- 關(guān)鍵字---and
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);
查詢一個屬性的子屬性,例如:查下面數(shù)據(jù)的key2.keyA的語句
var s = { key1: value1, key2: { keyA: valueA, keyB: valueB } }; @Query("{'key2.keyA':?0}") List<Asset> findAllBykeyA(String keyA);
5. 查詢數(shù)量:----- 關(guān)鍵字---count
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); }
查找包含在某個集合范圍:----- 關(guān)鍵字---in
Criteria criteria = new Criteria(); Object [] o = new Object[]{0, 1, 2}; //包含所有 criteria.and("type").in(o); Query query = new Query(criteria); query.with(new Sort(new Sort.Order(Direction.ASC, "type"))).with(new Sort(new Sort.Order(Direction.ASC, "title"))); List<WidgetMonitor> list = this.mongoTemplate.find(query, WidgetMonitor.class);
6. 更新一條數(shù)據(jù)的一個字段:
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); }
7. 更新一條數(shù)據(jù)的多個字段:
//調(diào)用更新 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); }
8. 刪除數(shù)據(jù):
public void deleteObject(Class<T> clazz,String id) { remove(new Query(Criteria.where("id").is(id)),clazz); }
9.保存數(shù)據(jù):
//插入一條數(shù)據(jù) public void saveObject(Object obj) { insert(obj); } //插入多條數(shù)據(jù) public void saveObjects(List<T> objects) { for(T t:objects){ insert(t); } }
我自己使用的例子:
下面例子涉及到:
精確查詢:is;
模糊查詢:regex;
分頁查詢,每頁多少:skip,limit
按某個字段排序(或升或降):new Sort(new Sort.Order(Sort.Direction.ASC, "port"))
查詢數(shù)量:count
public Map<String, Object> getAppPortDetailByPage(int pageNo, int pageSize, String order, String sortBy, String appPortType, String appPortSeacherName) { Criteria criteria = new Criteria(); if (!appPortType.equals("")) { if (!appPortType.equals("all")) { //DB表里的字段----appmanageType //下同 port protocol 也是DB表的字段 criteria.and("appmanageType").is(appPortType); } } if (!appPortSeacherName.equals("")) { try { criteria.orOperator(Criteria.where("port").is(Integer.parseInt(appPortSeacherName)), Criteria.where("protocol").regex(".*?" + appPortSeacherName + ".*")); }catch (Exception e){ criteria.orOperator(Criteria.where("protocol").regex(".*?" + appPortSeacherName + ".*")); } } Map<String, Object> result = Maps.newHashMap(); Query query = new Query(criteria); query.skip((pageNo - 1) * pageSize); query.limit(pageSize); if(order != null && sortBy != null){ query.with(new Sort(new Sort.Order(order.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sortBy))); }else { query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "port"))); } List<Appportmanage> list = this.mongoTemplate.find(query, Appportmanage.class); long count = this.mongoTemplate.count(query, Appportmanage.class); result.put("datas", list); result.put("size", count); return result; }
上述內(nèi)容就是怎么在java項目中利用mongodb進(jìn)行查詢操作,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
名稱欄目:怎么在java項目中利用mongodb進(jìn)行查詢操作
網(wǎng)站鏈接:http://muchs.cn/article30/ihccso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、云服務(wù)器、關(guān)鍵詞優(yōu)化、網(wǎng)站收錄、網(wǎng)站策劃、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)