在工作中我们会使用到很多的数据库,现在讲讲mongodb.
MongoDB是一个机遇分布式文件存储的数据库.由C++语言编写,旨在为WEB应用提供可扩展的高性能数据存储解决方案.
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.他支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型.MongoDB最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部份功能,而且支持对数据建立索引.
MongoDB的简单使用
1、引入依赖
org.springframework.boot
spring-boot-starter-data-mongodb
2、简单查询
Criteria criteria = Criteria.where("is_delete").ne(1);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("tenant_id").is("xxxxxxxxxx");
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
List<Long> tenantIds = Lists.newArrayList(1,2,3);
Criteria criteria = Criteria.where("id").in(tenantIds);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("id").gt(1);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("id").lt(200);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("id").gte(200);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("id").lte(200);
Query query = Query.query(criteria);
mongoTemplate.find(query, Tenant.class, "base_tenant");
Criteria criteria = Criteria.where("tenant_id").is("xxxxxxxxxx");
if(CollectionUtils.isNotEmpty(param.getIds())){
criteria.and("id").in(param.getIds());
}
Query query = Query.query(criteria);
query.skip(start).limit(length);
query.skip(bomAggregateQueryParam.getPagingParam().getStart()).limit(bomAggregateQueryParam.getPagingParam().getLength());
String sortField = "id";
Sort.Direction direction = Sort.Direction.DESC;
query.with(Sort.by(direction, sortField)); // 或者query.sort(排序)
mongoTemplate.find(query, Tenant.class, "base_tenant");
> 注意:
> skip(),limit(),sort()/with()三个放在一起的时候,执行顺序是先sort()/with(),然后是skip(),最后是limit()
9、模糊查询
在给模糊查询的之前,我们需要先了解一下mongodb数据库的模糊匹配的正则表达式
.(点号) 在正则表达式中是一个通配符,它代表所有字符和数字
*(星号) 表示前面的匹配符出现 >= 0次
+(加号) 表示前面的匹配符出现 >= 1次
?(问号) 表示前面的匹配符出现 <= 1次
{666} 表示前面的匹配符出现666次
{666}~{888} 表示前面的匹配符出现666 ~ 888次
^ 匹配开头,$ 匹配结尾
String keyword = "白帆瀚宇";
Query query = Query.query(Criteria.where("tenant_name").regex( "^.*" + keyword + ".*$" ));
result = mongoTemplate.find(query, Tenant.class);