项目中突然要使用Mongodb,所以这段时间把Mongodb简单的学了一下
先搭建mongodb环境,这个网上教程很多,直接百度即可
这边只简单记录和项目整合过程和使用过程
首先集成mongodb
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
添加数据库相关的配置信息
# mongodb config spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 spring.data.mongodb.username=fenghao spring.data.mongodb.password=123456 spring.data.mongodb.database=fenghao
因为是新添加的数据库,所以需要创建库,然后创建用户
db.createUser({user:"admin", pwd:"密码",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"readWriteAnyDatabase",db:"admin"}]});
接下来就是具体的业务代码了
首先创建相关的实体类,实体类可以添加相关的注解
@Document(collection="") --指定集合名称
@CompoundIndexes({
@CompoundIndex() --添加复合索引
})
@Id --添加唯一ID
@Indexed --添加索引
之后在要使用的类中注入
@Autowired
private MongoTemplate mongoTemplate;
添加数据
使用insert,save都可以
修改数据
Query query = Query.query(Criteria.where(查询条件).is(值)); --构建查询条件
Update update = new Update();
update.set(更新字段, info.getTime()); --构造要更新的数据
之后调用
updateFirst即可
删除数据
首选构造查询条件
之后调用remove即可
然后就是查询数据了
(1)分页查询数据
Sort sort = new Sort(Sort.Direction.DESC,排序字段); --排序
PageRequest of = PageRequest.of(pageNum, pageSize, sort);
Query query = Query.query(Criteria.where(查询条件).is(值));
long count = this.mongoTemplate.count(query, 实体类(带注解的));
long pageCount = (int) (count / pageSize + ((count % pageSize == 0) ? 0 : 1));
List<CollectionInfo> find = this.mongoTemplate.find(query.with(of), 实体类(带注解的));
分页数据有了,总页数也有了,总条数也有了
(2)具体Id查询
Query query = Query.query(Criteria.where(Id的名称).is(id));
this.mongoTemplate.findOne(query, 实体类(带注解的));
(3)多条件查询的
Query query = Query.query(Criteria.where(条件).is(值))
.addCriteria(Criteria.where(条件).is(值));
然后查询即可
(4)带分组的
long jump = (page - 1) * pageSize;
Aggregation newAggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where(条件字段).is(值)),
Aggregation.group(分组字段).max(最大值字段).as(别名(目前是和最大值保持一致)),
Aggregation.sort(Sort.Direction.DESC, 排序字段),
Aggregation.skip(jump),
Aggregation.limit(pageSize)
);
AggregationResults<JSONObject> aggregate = this.mongoTemplate.aggregate(newAggregation, 实体类(带注解的), JSONObject.class);
(5)查询时,指定返回的字段
Document dbObject = new Document();
dbObject.put(查询字段, 值);
Document fieldsObject=new Document();
fieldsObject.put(返回字段, true);
Query query = new BasicQuery(dbObject, fieldsObject);
List<RecordInfo> find = this.mongoTemplate.find(query,RecordInfo.class);
补充:
在SpringBoot连接mongodb的时候,报异常
Prohibited character at position 0
我这是密码的原因,需要将密码添加单引号即可
完!