前言:厌倦了关系的数据库Mysql,拿NOSql尝尝味道。本篇主要内容是如何引入MongoDB maven库、配置文件、使用、存储、查询。好了,人狠话不多,直接开工喽。
SpringBoot 2.2.2.RELEASE pom.xml 引入Mongodb maven
<code><
dependency
><
groupId
>org.springframework.bootgroupId
><
artifactId
>spring-boot-starter-data-mongodbartifactId
>dependency
>/<code>
清晰明了,简单方便
application.yml配置文件
<code>spring
:data
:mongodb
:uri
:mongodb
:/<code>
yml看起来确实清爽
MongoTemplate 操作MongoDB
<code>private
MongoTemplate mongoTemplate;/<code>
查询
<code> Query query =new
Query(); query.addCriteria(Criteria.where("_id"
).is(new
ObjectId(recordId))); TemplateData templateData = mongoTemplate.findOne(query, TemplateData.
class
); /<code>
添加、更新
<code> templateData.setCreateTime(DateUtil.date()); templateData.setUpdateTime(null
); mongoTemplate.save(templateData); Query query = new Query(); query.addCriteria(Criteria.where
("_id"
).is
(new ObjectId(recordId))); Update update = new Update(); update.set
("data"
, templateData.getData()); update.set
("updateTime"
, DateUtil.date()); UpdateResult updateResult = mongoTemplate.updateFirst(query, update, TemplateData.
class
); /<code>
删除、多条件
<code> Query query = new Query(); query.addCriteria(Criteria.where
("_id"
).is
(new ObjectId(recordId))); query.addCriteria(Criteria.where
("userId"
).is
(userId)); DeleteResult deleteResult = mongoTemplate.remove(query, TemplateData.
class
);/<code>
其它构造查询条件说明
<code>criteria
.ne
(cond.getValue());criteria
.regex
("/"
+ cond.getValue() +"/"
);if
(cond.getValue() instanceof List) {criteria
.lte
(((List) cond.getValue()).get(1
)).gte
(((List) cond.getValue()).get(0
)); }criteria
.in
(cond.getValue());criteria
.lte
(cond.getValue());criteria
.gte
(cond.getValue());/<code>
更多条件请去mongodb官方网站查询,本次提供了一些基本常用的条件
关于存储需要提醒大家
如果存储的内容为JSON,请一定要转为JSON或者Map或者JSONObject类似这种类型,否则入库之后
<code>"data"
:"{"ttt":"tttt"}"
/<code>
这时候再通过:data.ttt是查询不到
<code>"data"
:{"ttt"
:"tttt"
}/<code>