java操作mongdb 各種情況的增刪該查
阿新 • • 發佈:2018-12-18
精確查詢; 模糊查詢; 分頁查詢,每頁多少: 按某個欄位排序(或升或降): 查詢數量: 大於,小於, 等於; 且, 或, 某個欄位不為空, 某個欄位不存在, 查詢在某個範圍內, 刪除等等查詢。
- 根據條件查詢單條資料
public CrawlerSource getSource(Integer sourceId) { Query query=new Query(Criteria.where("source_id").is(sourceId)); DataSource dataSource = sourceDaoImpl.findOne(query); return dataSource ; } 如果多個條件 或者: public CrawlerSource getSource(Integer sourceId,String person_inCharge) { Query query=new Query(); Criteria criteria = new Criteria(); criteria.and("source_id").is(sourceId); criteria.and("person_inCharge").is(person_inCharge); query.addCriteria(criteria); DataSource dataSource = sourceDaoImpl.findOne(query); return dataSource ; }
- 模糊查詢:-----關鍵字—regex
public CrawlerSource getSource(Integer sourceId) { Query query=new Query(); Criteria criteria = new Criteria(); query.addCriteria(Criteria.where("name").regex(".*?" +sourceId.toString()+ ".*")); query.addCriteria(criteria); DataSource dataSource = sourceDaoImpl.findOne(query); return dataSource ; } 或者 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); }
- 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); }
- 條件“或”查詢----- ----- 關鍵字—orOperator
public CrawlerSource getSource(Integer sourceId,String person_inCharge) {
Query query=new Query();
Criteria criteria = new Criteria();
//查詢只顯示未刪除的和沒有刪除欄位的資料
criteria.orOperator(Criteria.where("deleted").is(false),
Criteria.where("deleted").exists(false));
query.addCriteria(criteria);
DataSource dataSource = sourceDaoImpl.findOne(query);
return dataSource ;
}
- 查詢欄位不存在的資料----關鍵字—not
public List<DataSource > getDataSource (int begin, int end) {
Query query = new Query();
query.addCriteria(Criteria.where("goodsSummary").not());
return find(query.limit(end - begin).skip(begin),DataSource .class);
}
- 查詢欄位不為空的資料 -----關鍵字—ne
Criteria.where("key1").ne("").ne(null)
- 查詢且語句:a && b ----- 關鍵字—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);
- 查詢一個屬性的子屬性,例如:查下面資料的key2.keyA的語句
var s = {
key1: value1,
key2: {
keyA: valueA,
keyB: valueB
}
};
@Query("{'key2.keyA':?0}")
List<Asset> findAllBykeyA(String keyA);
- 查詢數量:----- 關鍵字—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);
}
- 查詢包含在某個集合範圍:----- 關鍵字—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);
- 更新一條資料的一個欄位:
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);
}
- 更新一條資料的多個欄位:
//呼叫更新
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);
}
- 刪除資料:
public void deleteObject(Class<T> clazz,String id) {
remove(new Query(Criteria.where("id").is(id)),clazz);
}
- 儲存資料:
//插入一條資料
public void saveObject(Object obj) {
insert(obj);
}
//插入多條資料
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"))
查詢數量: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;
}