org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testApplication': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.nos.test.TestApplication$$EnhancerBySpringCGLIB$$c1828724]: Constructor threw exception; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Invalid numeric type, found: STRING; nested exception is org.bson.BsonInvalidOperationException: Invalid numeric type, found: STRING

题目要求:列出student集合中出现过的所有课程名称(distinct)

 public List<String> test6_01(){
        Query query = new Query();
        List<Integer> list_course = mongoTemplate.findDistinct(query,"CID","student_course",Integer.class);
        System.out.println(list_course);
        List<String> list = new ArrayList<>();
        for(Integer i:list_course){
            Query query1 = new Query(Criteria.where("CID").is(i));
            Course course = mongoTemplate.findOne(query1,Course.class,"course");
            list.add(course.getNAME());
        }
        return list;
    }

org.bson.BsonInvalidOperationException: Invalid numeric type, found: STRING提示我找到错误的数据类型,查找到的CID为String类型,才发现自己在数据中导入的数据,是把CID自动设为String类型的。

然后来看MongoDB中findDistinct()的具体用法:可以去重查询,但是无法排序。

该方法接收4个或5个参数,分别是:

1 query查询条件
2 需要去重的字段filed
3 查询的collection数据库表
4 查询的collection对应的pojo实例
5 返回结果类(返回需要去重的filed字段的list)

修改之后:

  public List<String> test6_01(){
        Query query = new Query();
        List<String> list_course = mongoTemplate.findDistinct(query,"CID","student_course",String.class);
        System.out.println(list_course);
        List<String> list = new ArrayList<>();
        for(String i:list_course){
            Query query1 = new Query(Criteria.where("CID").is(i));
            Course course = mongoTemplate.findOne(query1,Course.class,"course");
            list.add(course.getNAME());
        }
        return list;
    }

查询结果:

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐