pom.xml 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
初始化
@Autowired
private MongoTemplate mongoTemplate;
Query query = new Query();
Criteria criteria = new Criteria();
mongoTemplate.
查询操作
Pattern pattern = Pattern.compile("^.*"+这里拼接你的查询条件字符串+".*$", Pattern.CASE_INSENSITIVE);
criteria.and().regex()
query.addCriteria(criteria.and("这里填写你MongoDB集合中的key").regex(pattern));
criteria.and().is()
query.addCriteria(criteria.and("你MongoDB中的key").is("你的条件");
Criteria gt = Criteria.where("你MongoDB中的key").gt("你的条件");
Criteria lt = Criteria.where("你MongoDB中的key").lt("你的条件");
query.addCriteria(new Criteria().andOperator(gt,lt));
query.with(new Sort(Sort.Direction.ASC, "loginTime"));
query.with(new Sort(Sort.Direction.DESC, "loginTime"));
重写 find 方法(存在软删除时使用)
@Component
public class MongoDBTemp extends MongoTemplate {
public MongoDBTemp(MongoDbFactory mongoDbFactory) {
super(mongoDbFactory);
}
@Override
public <T> List<T> find(Query query, Class<T> entityClass) {
query.addCriteria(Criteria.where("delete").is(false));
return super.find(query, entityClass);
}
@Override
public <T> T findOne(Query query, Class<T> entityClass) {
query.addCriteria(Criteria.where("delete").is(false));
return super.findOne(query, entityClass);
}
}