- 配置连接
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>${spring.boot.version}</version></dependency>#mongodb 这里是没有设置密码spring.data.mongodb.host=localhostspring.data.mongodb.database=testspring.data.mongodb.port=27017
- 基础数据插入
@Document("base_info")@Datapublic class BaseInfo {private String id;@Field("source")private String source;@Field("create_time01")private String createTime01;@Field("language")private String language;@Field("time")private Integer time;@Field("create_time")private CreateTime createTime;}@Datapublic class CreateTime {@Field("$data")private String data;}@AutowiredMongoTemplate mongoTemplate;public String install(){BaseInfo baseInfo = new BaseInfo();baseInfo.setSource("qintin");baseInfo.setLanguage("en_tts");baseInfo.setTime(880);baseInfo.setCreateTime01(System.currentTimeMillis()+"");CreateTime time = new CreateTime();time.setData(System.currentTimeMillis()+"");baseInfo.setCreateTime(time);mongoTemplate.insert(baseInfo);return "sucess";}
- 基础数据查询
查询所有List<BaseInfo> list = mongoTemplate.findAll(BaseInfo.class);根据id查询BaseInfo list = mongoTemplate.findById("65ff8515ae6dbe5fa78a4256",BaseInfo.class);查询source为ximalaya,time<300{"source":"ximalaya","time":{"$lt":300}}Criteria criteria = Criteria.where("source").is("ximalaya");criteria.andOperator(Criteria.where("time").lt(300));Query query=new Query(criteria);query.with(Sort.by(Sort.Order.desc("time")));query.skip(2).limit(5);List<BaseInfo> list = mongoTemplate.find(query,BaseInfo.class);查询source为ximalaya,language为zh或者ko{"source":"ximalaya","language":{"$in":["jp","ko"]}}Criteria criteria = Criteria.where("source").is("ximalaya");criteria.andOperator(Criteria.where("language").in("jp","ko"));Query query=new Query(criteria);List<BaseInfo> list = mongoTemplate.find(query,BaseInfo.class);查询直接传入jsonString json = "{\"source\":\"ximalaya\",\"language\":{\"$in\":[\"jp\",\"ko\"]}}";Query query=new BasicQuery(json);List<BaseInfo> list = mongoTemplate.find(query,BaseInfo.class);
- 数据更新
Criteria criteria = Criteria.where("id").is("65ff8690ae6dbe5fa78a42fa");Query query=new Query(criteria);Update update = new Update();update.set("time","555");mongoTemplate.updateFirst(query,update,BaseInfo.class);mongoTemplate.updateMulti(query,update,BaseInfo.class);mongoTemplate.upsert(query,update,BaseInfo.class);
- 删除文档
Criteria criteria = Criteria.where("id").is("65ff8690ae6dbe5fa78a42fa");Query query=new Query(criteria);mongoTemplate.remove(query,BaseInfo.class);