mongoDB mongoTemplate操作


mongoTemplate  操作

 

****************************

相关类

 

Query:查询类

public class Query {

**********************
构造函数

    public Query() {
    }

    public Query(CriteriaDefinition criteriaDefinition) {
        this.addCriteria(criteriaDefinition);
    }


**********************
常用方法

    public static Query query(CriteriaDefinition criteriaDefinition)
    public Query addCriteria(CriteriaDefinition criteriaDefinition) {

    public Query skip(long skip) {
    public Query limit(int limit) {

×××××××××××
分页排序

    public Query with(Pageable pageable) {
    public Query with(Sort sort) {

 

criteria:条件构造类


public class Criteria implements CriteriaDefinition {

*******************
构造函数

    public Criteria() {
        this.isValue = NOT_SET;
        this.criteriaChain = new ArrayList();
    }

    public Criteria(String key) {
        this.isValue = NOT_SET;
        this.criteriaChain = new ArrayList();
        this.criteriaChain.add(this);
        this.key = key;
    }

    protected Criteria(List criteriaChain, String key) {
        this.isValue = NOT_SET;
        this.criteriaChain = criteriaChain;
        this.criteriaChain.add(this);
        this.key = key;
    }

*******************
常用方法
    public static Criteria where(String key) {
    public static Criteria byExample(Object example)
    public static Criteria byExample(Example example)

    public Criteria and(String key)

    public Criteria is(@Nullable Object o) {
    public Criteria ne(@Nullable Object o) {

    public Criteria lt(Object o) {
    public Criteria lte(Object o) {

    public Criteria gt(Object o) {
    public Criteria gte(Object o) {

    public Criteria in(Object... o) {
    public Criteria in(Collection c) {
    public Criteria nin(Object... o) {
    public Criteria nin(Collection o) {

    public Criteria mod(Number value, Number remainder) {
 
    public Criteria all(Object... o) {
    public Criteria all(Collection o) {

    public Criteria size(int s) {
    public Criteria exists(boolean b) {

    public Criteria type(int t) {
    public Criteria type(Type... types) {

    public Criteria not() {
    private Criteria not(@Nullable Object value) {

    public Criteria regex(String re) {
    public Criteria regex(String re, @Nullable String options) {
    public Criteria regex(Pattern pattern) {
    public Criteria regex(BsonRegularExpression regex) {

    public Criteria withinSphere(Circle circle) {
    public Criteria within(Shape shape) {
    public Criteria within(Shape shape) {

    public Criteria nearSphere(Point point) {
    public Criteria intersects(GeoJson geoJson) {

    public Criteria maxDistance(double maxDistance) {
    public Criteria minDistance(double minDistance) {

    public Criteria elemMatch(Criteria c) {
    public Criteria alike(Example sample) {

    public Criteria orOperator(Criteria... criteria) {
    public Criteria norOperator(Criteria... criteria) {
    public Criteria andOperator(Criteria... criteria) {


***********************************
criteriaDefinition接口

public interface CriteriaDefinition {
    Document getCriteriaObject();

    @Nullable
    String getKey();
}

 

update:更新类

public class Update implements UpdateDefinition {

**********************
构造函数

    public Update() {
    }

**********************
常用方法

    public static Update update(String key, Object value) {
        return (new Update()).set(key, value);
    }             //更新字段

    public Update set(String key, Object value) {
    public Update setOnInsert(String key, Object value) {
                  //设置字段值,字段不存在则新建字段

    public Update unset(String key) {
                  //删除字段

    public void inc(String key) {
    public Update inc(String key, Number inc) {
                  //字段值自增

    public Update push(String key, Object value) {
                  //将value值追加到key数组中,如果key不存在,新建key

    public Update.AddToSetBuilder addToSet(String key) {
    public Update addToSet(String key, Object value) {
                  //将value添加到数组中,若数组中已存在则不添加

    public Update pop(String key, Update.Position pos) {
                  //删除数组的第一(-1) 或者最后一个元素(1)

    public Update pull(String key, Object value) {
    public Update pullAll(String key, Object[] values) {
                  //数组中删除元素

    public Update rename(String oldName, String newName) {
                  //重命名字段

    public Update currentDate(String key) {
    public Update currentTimestamp(String key) {

    public Update multiply(String key, Number multiplier) {
    public Update max(String key, Object value) {
    public Update min(String key, Object value) {

 

mongoTemplate:增删查改操作类

public class MongoTemplate implements MongoOperations, ApplicationContextAware, IndexOperationsProvider {

    private final QueryMapper queryMapper;
    private final UpdateMapper updateMapper;

    @Nullable
    private WriteConcern writeConcern;

    @Nullable
    private ReadPreference readPreference;

********************
构造函数

    public MongoTemplate(MongoClient mongoClient, String databaseName) {
    public MongoTemplate(com.mongodb.client.MongoClient mongoClient, String databaseName) {
    public MongoTemplate(MongoDbFactory mongoDbFactory) {
    public MongoTemplate(MongoDbFactory mongoDbFactory, @Nullable MongoConverter mongoConverter) {
    private MongoTemplate(MongoDbFactory dbFactory, MongoTemplate that) {

********************
常用方法

    public void setWriteConcern(@Nullable WriteConcern writeConcern) {
                    //设置副本集写入副本的数量,达到指定数量写入成功

    public void setReadPreference(@Nullable ReadPreference readPreference) {
                    //可设置读副本,实现读写分离

*************
查询数据

    public  T findOne(Query query, Class entityClass) {
    public  T findOne(Query query, Class entityClass, String collectionName) {

    public  List find(Query query, Class entityClass) {
    public  List find(Query query, Class entityClass, String collectionName) {

    public  T findById(Object id, Class entityClass) {
    public  T findById(Object id, Class entityClass, String collectionName) {

    public  List findDistinct(Query query, String field, Class entityClass, Class resultClass) {
    public  List findDistinct(Query query, String field, String collectionName, Class entityClass, Class resultClass) {

    public  List findAll(Class entityClass) {
    public  List findAll(Class entityClass, String collectionName) {

************* 
查询并修改

    public  T findAndModify(Query query, Update update, Class entityClass) {
    public  T findAndModify(Query query, Update update, Class entityClass, String collectionName) {
    public  T findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass) {
    public  T findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass, String collectionName) {

*************
查询并替换、删除

    public  T findAndReplace(Query query, S replacement, FindAndReplaceOptions options, Class entityType, String collectionName, Class resultType) {

    public  T findAndRemove(Query query, Class entityClass) {
    public  T findAndRemove(Query query, Class entityClass, String collectionName) {

*************
地理位置查询

    public  GeoResults geoNear(NearQuery near, Class entityClass) {
    public  GeoResults geoNear(NearQuery near, Class domainType, String collectionName) {
    public  GeoResults geoNear(NearQuery near, Class domainType, String collectionName, Class returnType) {

*************
插入数据

    public  T insert(T objectToSave) {
    public  T insert(T objectToSave, String collectionName) {
    public  Collection insert(Collection batchToSave, Class entityClass) {
    public  Collection insert(Collection batchToSave, String collectionName) {

    public  Collection insertAll(Collection objectsToSave) {


*************
保存数据

    public  T save(T objectToSave) {
    public  T save(T objectToSave, String collectionName) {


*************
更新插入(不存在则插入)

    public UpdateResult upsert(Query query, Update update, Class entityClass) {
    public UpdateResult upsert(Query query, Update update, String collectionName) {
    public UpdateResult upsert(Query query, Update update, Class entityClass, String collectionName) {


*************
更新数据

    public UpdateResult updateFirst(Query query, Update update, Class entityClass) {
    public UpdateResult updateFirst(Query query, Update update, String collectionName) {
    public UpdateResult updateFirst(Query query, Update update, Class entityClass, String collectionName) {

    public UpdateResult updateMulti(Query query, Update update, Class entityClass) {
    public UpdateResult updateMulti(Query query, Update update, String collectionName) {
    public UpdateResult updateMulti(Query query, Update update, Class entityClass, String collectionName) {


*************
删除数据

    public DeleteResult remove(Object object) {
    public DeleteResult remove(Object object, String collectionName) {
    public DeleteResult remove(Query query, String collectionName) {
    public DeleteResult remove(Query query, Class entityClass) {
    public DeleteResult remove(Query query, Class entityClass, String collectionName) {

*************
查找并删除数据

    public  List findAllAndRemove(Query query, String collectionName) {
    public  List findAllAndRemove(Query query, Class entityClass) {
    public  List findAllAndRemove(Query query, Class entityClass, String collectionName) {


*************
判断对象是否存在

    public boolean exists(Query query, Class entityClass) {
    public boolean exists(Query query, String collectionName) {
    public boolean exists(Query query, @Nullable Class entityClass, String collectionName) {

*************
统计数量

    public long count(Query query, Class entityClass) {
    public long count(Query query, String collectionName) {
    public long count(Query query, @Nullable Class entityClass, String collectionName) {


*************
mapReduce操作

    public  MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass) {
    public  MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class entityClass) {
    public  MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass) {
    public  MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class entityClass) {
    public  List mapReduce(Query query, Class domainType, String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class resultType) {


*************
分组操作

    public  GroupByResults group(String inputCollectionName, GroupBy groupBy, Class entityClass) {
    public  GroupByResults group(@Nullable Criteria criteria, String inputCollectionName, GroupBy groupBy, Class entityClass) {

*************
聚合操作

    public  AggregationResults aggregate(TypedAggregation aggregation, Class outputType) {
    public  AggregationResults aggregate(TypedAggregation aggregation, String inputCollectionName, Class outputType) {
    public  AggregationResults aggregate(Aggregation aggregation, Class inputType, Class outputType) {
    public  AggregationResults aggregate(Aggregation aggregation, String collectionName, Class outputType) {

    public  CloseableIterator aggregateStream(TypedAggregation aggregation, String inputCollectionName, Class outputType) {
    public  CloseableIterator aggregateStream(TypedAggregation aggregation, Class outputType) {
    public  CloseableIterator aggregateStream(Aggregation aggregation, Class inputType, Class outputType) {
    public  CloseableIterator aggregateStream(Aggregation aggregation, String collectionName, Class outputType) {

 

 

****************************

使用示例 

 

*******************

controller 层

 

@RestController
public class HelloController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("/save")
    public String save(){
        for(int i=0;i<100;i++){
            Person person=new Person();
            person.setId(i);
            person.setName("瓜田李下"+i);
            person.setAge(i%10+16);
            
            mongoTemplate.save(person);
        }
        
        return "success";
    }


**************************
查询所有数据

    @RequestMapping("/getAll")
    public List getAll(){
        return mongoTemplate.findAll(Person.class);
    }

**************************
模糊查询
    
    @RequestMapping("/get")
    public List get(){
        Query query=Query.query(Criteria.where("name").regex("瓜田李下"));
        return mongoTemplate.find(query,Person.class);
    }

***************************
动态查询
    
    @RequestMapping("/get2")
    public List get2(String name,Integer age){
        Criteria criteria = new Criteria();
        Criteria c1=new Criteria();
        Criteria c2=new Criteria();
        if(name!=null){
            c1=Criteria.where("name").regex(name);
        }
        
        if (age!=null){
            c2=Criteria.where("age").is(age);
        }

        criteria=criteria.andOperator(c1,c2);
        return mongoTemplate.find(Query.query(criteria),Person.class);
    }

****************************
排序

    @RequestMapping("/get3")
    public List get3(){
        Query query=Query.query(Criteria.where("age").is(16));
        Sort sort=Sort.by("age").descending().and(Sort.by("name").ascending());
        query.with(sort);
        return mongoTemplate.find(query,Person.class);
    }

**********************************
排序分页

    @RequestMapping("/get4")
    public List get4(){
        PageRequest pageRequest=PageRequest.of(2,10);
        Sort sort=Sort.by("age").ascending();
        Query query=new Query().with(pageRequest).with(sort);

        return mongoTemplate.find(query,Person.class);
    }

**************************
更新操作

    @RequestMapping("/update")
    public Person update(){
        Query query=Query.query(Criteria.where("age").is(18));
        Update update=new Update().set("name","海贼王").set("interest","海贼王");

        mongoTemplate.updateMulti(query,update,Person.class);
        return mongoTemplate.findOne(query,Person.class);
    }
}

 

 

你可能感兴趣的:(mongoDB)