• spring data mongo API learn(转)


    显示操作mongo的语句,log4j里面加入:

    log4j.logger.org.springframework.data.mongodb.core=DEBUG, mongodb
    log4j.appender.mongodb=org.apache.log4j.ConsoleAppender
    log4j.appender.mongodb.Target=System.out
    log4j.appender.mongodb.Threshold=DEBUG
    log4j.appender.mongodb.ImmediateFlush=true
    log4j.appender.mongodb.layout=org.apache.log4j.PatternLayout
    log4j.appender.mongodb.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %X{RequestId} - %m%n

    MongoOptions/MongoTemplate:

    常见查询方法:

    public <T> T findOne(Query query, Class<T> entityClass) 
    public boolean exists(Query query, Class<?> entityClass)
    public <T> List<T> find(Query query, Class<T> entityClass)
    public <T> T findById(Object id, Class<T> entityClass)
     
     
    public <T> T findAndModify(Query query, Update update, Class<T> entityClass)
    public <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass)
     
     
    public class FindAndModifyOptions {
    <strong><span style="white-space:pre">    </span>boolean returnNew;   // 是否返回更新后的值
    <span style="white-space:pre">    </span>boolean upsert;      // 没有找到是否插入 
    <span style="white-space:pre">    </span>boolean remove;      // 找到是否删除</strong>
    }
     
     
    public <T> T findAndRemove(Query query, Class<T> entityClass)
    public long count(Query query, Class<?> entityClass) 
     
     
    public void insert(Object objectToSave) 
    public void insert(Collection<? extends Object> batchToSave, Class<?> entityClass)
    public void insertAll(Collection<? extends Object> objectsToSave)
     
     
    public void save(Object objectToSave)
     
     
     
     
    public WriteResult upsert(Query query, Update update, Class<?> entityClass) 
    public WriteResult updateFirst(Query query, Update update, Class<?> entityClass)
    public WriteResult updateMulti(Query query, Update update, Class<?> entityClass)
     
     
    public WriteResult remove(Object object)
    public WriteResult remove(Query query, String collectionName)
     
     
     
     
    public <T> List<T> findAll(Class<T> entityClass)
    public <T> List<T> findAllAndRemove(Query query, Class<T> entityClass) 
     
     
    public DB getDb()
    public String getCollectionName(Class<?> entityClass)
     
     
     
     
    public <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, Class<T> entityClass)
    public <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,MapReduceOptions mapReduceOptions, Class<T> entityClass) 
     
     
    public <T> GroupByResults<T> group(String inputCollectionName, GroupBy groupBy, Class<T> entityClass)
     
     
     
     
    public <O> AggregationResults<O> aggregate(TypedAggregation<?> aggregation, Class<O> outputType)
    public <O> AggregationResults<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType)

    注解式查询:

    1 一个方法名查询中同一个属性不能出现2次  可以创意@Query方法查询
    2 @Query:
         value  查询语句
         count  作为统计的查询 返回int值
         delete 作为删除语句并返回删除后的文档集合
         fields 返回哪些字段
     
     
      示例:
        @Query(count = true, value = "{'$and':[{'tenant':?3},{'reportStatus':?0}," +
                " {'dealTime':{'$gte':?1}}, {'dealTime':{'$lte':?2}}]}")
        int countByStatusAndDealTimeBetween
                (ReportStatus status, Date begin, Date end, long tenant);

    Sort:

    private final List<Order> orders;
     
     
    public Sort and(Sort sort) {
     
     
            if (sort == null) {
                return this;
            }
     
     
            ArrayList<Order> these = new ArrayList<Order>(this.orders);
     
     
            for (Order order : sort) {
                these.add(order);
            }
     
     
            return new Sort(these);
        }

    Query:

    private Sort sort;
        private int skip;
        private int limit;
     
     
        public Query skip(int skip) {
            this.skip = skip;
            return this;
        }
     
     
        public Query limit(int limit) {
            this.limit = limit;
            return this;
        }
     
     
            public Query with(Pageable pageable) {
     
     
            if (pageable == null) {
                return this;
            }
     
     
            this.limit = pageable.getPageSize();
            this.skip = pageable.getOffset();
     
     
            return with(pageable.getSort());
        }
     
     
        public Query with(Sort sort) {
     
     
            if (sort == null) {
                return this;
            }
     
     
            for (Order order : sort) {
                if (order.isIgnoreCase()) {
                    throw new IllegalArgumentException(String.format("Gven sort contained an Order for %s with ignore case! "
                            + "MongoDB does not support sorting ignoreing case currently!", order.getProperty()));
                }
            }
     
     
            if (this.sort == null) {
                this.sort = sort;
            } else {
                this.sort = this.sort.and(sort);
            }
     
     
            return this;
        }
     
     
     
    private final Map<String, CriteriaDefinition> criteria = new LinkedHashMap<String, CriteriaDefinition>();
     
     
        public static Query query(CriteriaDefinition criteriaDefinition) {
            return new Query(criteriaDefinition);
        }
     
     
        public Query() {}
     
     
     
     
        public Query(CriteriaDefinition criteriaDefinition) {
            addCriteria(criteriaDefinition);
        }
     
     
     
     
        public Query addCriteria(CriteriaDefinition criteriaDefinition) {
     
     
            CriteriaDefinition existing = this.criteria.get(criteriaDefinition.getKey());
            String key = criteriaDefinition.getKey();
     
     
            if (existing == null) {
                this.criteria.put(key, criteriaDefinition);
            } else {
                throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDBObject, "
                        + "you can't add a second '" + key + "' criteria. " + "Query already contains '"
                        + existing.getCriteriaObject() + "'.");
            }
     
     
            return this;
        }

    Criteria:

    private String key;
        private List<Criteria> criteriaChain;
        private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
        private Object isValue = NOT_SET;
     
     
            public static Criteria where(String key) {
            return new Criteria(key);
        }
     
     
        /**
         * Static factory method to create a Criteria using the provided key
         * 
         * @return
         */
        public Criteria and(String key) {
            return new Criteria(this.criteriaChain, key);
        }
     
     
    andOperator
     
     
    is ne lt lte gt gte in nin mod all size exits type not regex

    聚合:

    /** 
             * db.videos.aggregate( 
                [ 
                   { $match: { "frags.isnew" : true } }, 
                   { $unwind: "$frags" }, 
                   { $match: { "frags.isnew" : true } }, 
                   { $group: {  
                               _id: {cat1:"$cat1"}, 
                               count: { $sum: 1 }, 
                               publishdate2: { $max: "$publishdate"} 
                             } 
                   } 
                    
                ] 
                ) 
             */  
            Aggregation agg = newAggregation(  
                    project("frags","cat1","publishdate"),//挑选所需的字段  
                    match(  
                            Criteria.where("frags.isnew").is(Boolean.TRUE)  
                            .and("cat1").in(importantCat1List)  
                         ),//筛选符合条件的记录  
                    unwind("frags"),//如果有MASTER-ITEM关系的表,需同时JOIN这两张表的,展开子项LIST,且是内链接,即如果父和子的关联ID没有的就不会输出  
                    match(Criteria.where("frags.isnew").is(Boolean.TRUE)),  
                    group("cat1")//设置分组字段  
                        .count().as("updateCount")//增加COUNT为分组后输出的字段  
                        .last("publishdate").as("publishDate"),//增加publishDate为分组后输出的字段  
                    project("publishDate","cat1","updateCount")//重新挑选字段  
                        .and("cat1").previousOperation()//为前一操作所产生的ID FIELD建立别名  
                ); 

    ————————————————
    版权声明:本文为CSDN博主「weihainan」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010084868/article/details/52625819

  • 相关阅读:
    NanUI for Winform发布,让Winform界面设计拥有无限可能
    使用Nginx反向代理 让IIS和Tomcat等多个站点一起飞
    jQuery功能强大的图片查看器插件
    Entity Framework 5.0 Code First全面学习
    封装EF code first用存储过程的分页方法
    NET中使用Redis (二)
    Redis学习笔记~Redis主从服务器,读写分离
    ID3算法
    定性归纳(1)
    js加密
  • 原文地址:https://www.cnblogs.com/muxi0407/p/11750455.html
Copyright © 2020-2023  润新知