java MongoDB 字符串日期类型查询和日期类型查询

来源:互联网 发布:林俊杰baby知乎 编辑:程序博客网 时间:2024/05/19 01:08

1、基于字符串类型时间日期格式查询,在MongoDB 库中存储的时间是字符串类型,格式如以下格式


2、实体类相对应的属性也应该用String类型


package com.avic.api.entity.base;import com.avic.core.entity.Entity;import java.util.Date;import org.springframework.data.annotation.Id;import org.springframework.data.annotation.Transient;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "CT_UserLog") public class BaseUserLog extends Entity {private static final long serialVersionUID = 1L;/** id-id **/@Idprivate String id;/** 用户id-用户id **/private Integer userId;/** 操作类型-操作类型 **/private String typeFlg;/** 操作内容-操作内容 **/private String content;/** 操作时间-操作时间 **/private String logTime;/** 最后登录ip-最后登录ip **/private String ip;/** 登录城市-登录城市 **/private String city;/** 来源-来源 **/private Integer source;/** 设备标识-设备标识 **/private String deviceId;/** 设备型号-设备型号 **/private String deviceModel;/** 设备系统-设备系统 **/private String deviceSystem;/** 最近登录运营商-最近登录运营商 **/private String operator;/** 最近登录网络-最近登录网络 **/private String network;private String operationJsp;//操作页面@Transientprivate String beginTime;//开始时间@Transientprivate String endTime;//结束时间public BaseUserLog() {}public String getId() {return id;}public void setId(String id) {this.id = id;}public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getTypeFlg() {return typeFlg;}public void setTypeFlg(String typeFlg) {this.typeFlg = typeFlg;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}    public String getLogTime() {return logTime;}public void setLogTime(String logTime) {this.logTime = logTime;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Integer getSource() {return source;}public void setSource(Integer source) {this.source = source;}public String getDeviceId() {return deviceId;}public void setDeviceId(String deviceId) {this.deviceId = deviceId;}public String getDeviceModel() {return deviceModel;}public void setDeviceModel(String deviceModel) {this.deviceModel = deviceModel;}public String getDeviceSystem() {return deviceSystem;}public void setDeviceSystem(String deviceSystem) {this.deviceSystem = deviceSystem;}public String getOperator() {return operator;}public void setOperator(String operator) {this.operator = operator;}public String getNetwork() {return network;}public void setNetwork(String network) {this.network = network;}public String getOperationJsp() {return operationJsp;}public void setOperationJsp(String operationJsp) {this.operationJsp = operationJsp;}public String getBeginTime() {return beginTime;}public void setBeginTime(String beginTime) {this.beginTime = beginTime;}public String getEndTime() {return endTime;}public void setEndTime(String endTime) {this.endTime = endTime;}    }

3、页面传输的时间格式(一般都是用日期格式插件):

<form id="search_form" action="">            <div class="col-xs-12 col-sm-6  mt-10 cl_row pos-r" >                    <div class="col-xs-2 col-sm-2 cl_row text-r">                        <span>操作时间:</span>                    </div>                    <div class="col-xs-4 col-sm-5">                        <input type="text" onfocus="WdatePicker({ maxDate:'#F{$dp.$D(\'logmax\')||\'%y-%M-%d\'}' })" id="logmin" name="beginTime" class="Wdate input-text">                    </div>                    <div class="pos-a" style="left: 58%">-</div>                    <div class="col-xs-4 col-sm-5">                        <input type="text" onfocus="WdatePicker({ minDate:'#F{$dp.$D(\'logmin\')}',maxDate:'%y-%M-%d' })" id="logmax" name="endTime" class="Wdate input-text">                    </div>                </div>                <div class="r col-xs-12 col-sm-3 mt-10 mb-5">                    <button class="btn btn-danger radius"  type="reset"> 重 置 </button>                    <button  id="search_btn" class="btn btn-success radius ml-10" type="button">  搜 索 </button>                </div>            </form>

图片效果:



4、service查询方法(已经用spring和MongoTemplate整合好的,可以参考网上整合版的进行封装):

@Overridepublic SimplePage<BaseUserLog> findPagee(BaseUserLog baseUserLog) throws Exception {DBObject obj = new BasicDBObject();SimpleDateFormat format =  new SimpleDateFormat( "yyyy-MM-dd HH:mm" );SimplePage<BaseUserLog> page = new SimplePage<BaseUserLog>(baseUserLog.getStart(),baseUserLog.getOffset());/*Query query = new BasicQuery(obj);    Criteria criteria=new Criteria();//开始时间查询if(StringUtils.isNotBlank(baseUserLog.getBeginTime())){criteria =Criteria.where("logTime").gte(format.parse(baseUserLog.getBeginTime()));DBObject objl = new BasicDBObject();objl.put("$gte", baseUserLog.getBeginTime());obj.put("logTime", objl);}//结束时间查询if(StringUtils.isNotBlank(baseUserLog.getEndTime())){criteria= Criteria.where("logTime").lt(format.parse(baseUserLog.getEndTime()));DBObject objl = new BasicDBObject();objl.put("$lt", baseUserLog.getEndTime());obj.put("logTime", objl);}if(StringUtils.isNotBlank(baseUserLog.getBeginTime())&&StringUtils.isNotBlank(baseUserLog.getEndTime())){criteria = Criteria.where("logTime").gte(format.parse(baseUserLog.getBeginTime())).lt(format.parse(baseUserLog.getEndTime())); }*/DBObject objl = new BasicDBObject();//开始时间查询if(StringUtils.isNotBlank(baseUserLog.getBeginTime())){objl.put("$gte", baseUserLog.getBeginTime());obj.put("logTime", objl);}//结束时间查询if(StringUtils.isNotBlank(baseUserLog.getEndTime())){objl.put("$lte", baseUserLog.getEndTime());obj.put("logTime", objl);}obj.put("userId", baseUserLog.getUserId());//query.addCriteria(criteria);Query query = new BasicQuery(obj);//query.addCriteria(Criteria.where("userId").is(baseUserLog.getUserId()));query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"logTime")));page = mongoUserLogDao.findPage(page, query);return page;}

5、最终效果:


根据Mongo存储的时间类型为ISODate

{    "_id" : ObjectId("592ab8a0ef90f06a32ec11ff"),    "ident" : "862458032934256",    "_class" : "com.avic.api.entity.AppUser",    "channel" : "m360",    "type" : "2",    "userId" : 0,    "isMem" : 0,    "startNum" : 163,    "lastTime" : ISODate("2017-06-02T06:45:41.000Z"),    "addTime" : ISODate("2017-05-28T11:48:35.000Z")}

对应的属性也应该为Date类型

package com.avic.api.entity.base;import java.util.Date;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;import com.avic.core.entity.Entity;@Document(collection = "CT_AppUser")  public class BaseAppUser extends Entity {private static final long serialVersionUID = 1L;    @Idprivate String id;private String ident;private Integer userId;private Integer isMem;private String type;private String channel;//渠道private Long startNum;//启动次数private Date lastTime;private Date addTime;public BaseAppUser() {}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getIdent() {return ident;}public void setIdent(String ident) {this.ident = ident;}public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public Integer getIsMem() {return isMem;}public void setIsMem(Integer isMem) {this.isMem = isMem;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getChannel() {return channel;}public void setChannel(String channel) {this.channel = channel;}public Long getStartNum() {return startNum;}public void setStartNum(Long startNum) {this.startNum = startNum;}public Date getLastTime() {return lastTime;}public void setLastTime(Date lastTime) {this.lastTime = lastTime;}public Date getAddTime() {return addTime;}public void setAddTime(Date addTime) {this.addTime = addTime;}}

对应的service查询方法

@Overridepublic SimplePage<AppUser> selectPaginatedList(AppUser appUser) throws Exception {    SimplePage<AppUser> page = new SimplePage<AppUser>(appUser.getStart(),appUser.getOffset());SimpleDateFormat format =  new SimpleDateFormat( "yyyy-MM-dd" );DBObject obj = new BasicDBObject();Criteria criteria=new Criteria();//obj.put("isMem", 0);if(StringUtils.isNotBlank(appUser.getType())){obj.put("type", appUser.getType());}if(null!=appUser.getChannel() && !appUser.getChannel().equals("")){obj.put("channel", appUser.getChannel());}//开始时间查询if(StringUtils.isNotBlank(appUser.getLoginTimeStart())){criteria =Criteria.where("lastTime").gte(format.parse(appUser.getLoginTimeStart()));}//结束时间查询if(StringUtils.isNotBlank(appUser.getLoginTimeEnd())){criteria =Criteria.where("lastTime").lt(format.parse(appUser.getLoginTimeEnd()));}if(StringUtils.isNotBlank(appUser.getLoginTimeStart())&&StringUtils.isNotBlank(appUser.getLoginTimeEnd())){criteria = Criteria.where("lastTime").gte(format.parse(appUser.getLoginTimeStart())).lt(format.parse(appUser.getLoginTimeEnd())); }Query query = new BasicQuery(obj);query.addCriteria(criteria);page = mongoAppUserDao.findPage(page, query);        return page;     }








阅读全文
1 0