随便测试了一下,有问题请指出

pom.xml中添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.projectlombok</groupId>
  7. <artifactId>lombok</artifactId>
  8. <version>1.18.2</version>
  9. </dependency>

application.yml中添加连接信息

  1. spring:
  2. data:
  3. mongodb:
  4. uri: mongodb://xxx:27017/school

测试类

  1. @SpringBootTest
  2. @RunWith(SpringRunner.class)
  3. public class MongoDBTest {
  4. @Autowired
  5. private MongoTemplate mongoTemplate;
  6. /*@Autowired
  7. private MongoRepository mongoRepository;*/
  8. @Autowired
  9. private GridFsTemplate gridFsTemplate;
  10. ....
  11. }

添加

通过三种形式来添加数据到mongo

  1. @Test
  2. public void add() {
  3. // 1. 这种插入的数据的id 就直接是mongodb中的_id
  4. Student student = new Student(1, "鲁班7号", "1", 80D, Arrays.asList("玩", "虚坤", "天书世界", "贪玩蓝月"));
  5. mongoTemplate.insert(student);
  6. // 2. 使用类似map的写法,这种插入的id,是mongodb中的一个字段,会另外自动生成_id
  7. BasicDBObject obj = new BasicDBObject();
  8. obj.put("id", 2);
  9. obj.put("name", "cxk");
  10. obj.put("score", 95);
  11. obj.put("clazz", "2");
  12. String[] hobby = {"唱", "跳", "篮球", "rap"};
  13. obj.put("hobby", hobby);
  14. mongoTemplate.insert(obj, "student");
  15. // 3. 使用json数据 会自动另外生成_id
  16. BasicDBObject parse = BasicDBObject.parse("{\n" +
  17. " \"id\": 3,\n" +
  18. " \"clazz\": \"2\",\n" +
  19. " \"score\": 90,\n" +
  20. " \"name\": \"渣渣辉\",\n" +
  21. " \"hobby\":[\"贪\",\"玩\",\"蓝\", \"月\"]\n" +
  22. "}");
  23. mongoTemplate.insert(parse, "student");
  24. }

student.java

  1. @Getter
  2. @Setter
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. @ToString
  6. @Builder
  7. public class Student {
  8. // 与mongodb中的_id对应
  9. private Integer id;
  10. private String name;
  11. /**
  12. * 班级
  13. */
  14. private String clazz;
  15. private Double score;
  16. private List<String> hobby;
  17. }

删除

  1. @Test
  2. public void delete() {
  3. // 根据id删除
  4. // DeleteResult id = mongoTemplate.remove(Query.query(Criteria.where("_id").is(1)), "student");
  5. Query query = new Query();
  6. mongoTemplate.remove(query, "student");
  7. }

文档操作更新

  1. /**
  2. * 文档操作
  3. */
  4. @Test
  5. public void update() {
  6. // 只修改第一个条记录
  7. mongoTemplate.updateFirst(Query.query(Criteria.where("id").gt(2)), Update.update("name", "鸡太美"), "student");
  8. // 修改匹配到的所有数据
  9. mongoTemplate.updateMulti(Query.query(Criteria.where("id").gt(2)), Update.update("name", "鸡太美"), "student");
  10. // 向文档中添加数据 有则跟新 没有则添加
  11. Update update = new Update();
  12. update.addToSet("desc", "练习时长两年半的练习生");
  13. mongoTemplate.upsert(Query.query(Criteria.where("id").gte(2)), update, "student");
  14. // 删除文档中的数据
  15. Update delUpdate = new Update();
  16. delUpdate.unset("desc");
  17. mongoTemplate.updateMulti(Query.query(Criteria.where("id").gt(2)), delUpdate, "student");
  18. }

简单聚合操作 count, distinct

  1. /**
  2. * 简单聚合操作 count, distinct
  3. */
  4. @Test
  5. public void runCommongd() {
  6. /************* count *********************/
  7. // student集合中的总人数 select count(1) from student
  8. Document document = mongoTemplate.executeCommand("{count: 'student'}");
  9. mongoTemplate.getCollection("student").countDocuments();
  10. System.out.println(document);
  11. // 班级为2的人数 注意字符串要有引号 js中单引号和双引号没啥区别 select count(1) from student where clazz = '2'
  12. Document document1 = mongoTemplate.executeCommand("{count: 'student', query:{clazz: {$eq:'2'}}}");
  13. System.out.println(document1);
  14. /************* distinct **************/
  15. // 去掉重复的班级 select distinct clazz from student
  16. Document document2 = mongoTemplate.executeCommand("{distinct: 'student', key: 'clazz'}");
  17. mongoTemplate.getCollection("person").distinct("clazz", Document.class);
  18. System.out.println(document2);
  19. }

普通查询

  1. /**
  2. * 查询
  3. */
  4. @Test
  5. public void findTest() {
  6. // 这个id默认是mognodb中的_id
  7. Student student = mongoTemplate.findById(1, Student.class, "student");
  8. System.out.println(student);
  9. Document doc = mongoTemplate.findById("5da57cb7f150ea3be420daf8", Document.class, "student");
  10. //Document{{_id=5da57cb7f150ea3be420daf8, id=2, name=cxk, hobby=[唱, 跳, rap]}}
  11. System.out.println(doc);
  12. // Criteria用来构建条件 Query 用来封装所有条件
  13. Query query = new Query(Criteria.where("_id").is("5da57cb7f150ea3be420daf9"));
  14. Document one = mongoTemplate.findOne(query, Document.class, "student");
  15. System.out.println(one);
  16. // 正则表达式查询 (查询名字中有数字的数据) 如果不需要后面的Pattern.CASE_INSENSITIVE,直接写正则字符串就行
  17. //Criteria regCriteria = Criteria.where("name").regex(Pattern.compile(".*\\d+.*", Pattern.CASE_INSENSITIVE));
  18. Criteria regCriteria = Criteria.where("name").regex(".*\\d+.*");
  19. Query regQuery = new Query(regCriteria);
  20. List<Student> student1 = mongoTemplate.find(regQuery, Student.class, "student");
  21. System.out.println(student1);
  22. // 查询文档中的部分记录
  23. BasicDBObject dbObject = new BasicDBObject();
  24. // 添加查询条件 等于的那种
  25. //dbObject.put("id", 2);
  26. // 指定返回的字段
  27. BasicDBObject fieldsObject = new BasicDBObject();
  28. fieldsObject.put("id", true);
  29. fieldsObject.put("name", true);
  30. fieldsObject.put("_id", false);
  31. Query basicQuery = new BasicQuery(dbObject.toJson(), fieldsObject.toJson());
  32. // 添加查询条件 更灵活
  33. query.addCriteria(Criteria.where("id").gt(2));
  34. List<Document> docs = mongoTemplate.find(basicQuery, Document.class, "student");
  35. System.out.println(docs);
  36. }

分组

group

  1. /**
  2. * group分组
  3. */
  4. @Test
  5. public void group() {
  6. // 查找80分以上的人的平均得分
  7. GroupBy groupBy = GroupBy.key("clazz")
  8. .initialDocument("{total:0, count:0}")
  9. // curr表示当前doc文档,result表示上一次处理之后的{total:0, count:0}对象
  10. .reduceFunction("function(curr, result) {result.total += curr.score; result.count++}")
  11. // 类似于having,比having更强大,js语法去操作最后的结果
  12. .finalizeFunction("function(result) {result.avg = Math.round(result.total/result.count);}");
  13. Criteria criteria = Criteria.where("score").gte(80);
  14. GroupByResults<Document> brs = mongoTemplate.group(criteria, "student", groupBy, Document.class);
  15. for (Document document : brs) {
  16. System.out.println(document);
  17. }
  18. }

Aggregate

  1. /**
  2. * aggregate聚合查询
  3. */
  4. @Test
  5. public void aggregateTest() {
  6. //封装查询条件
  7. // 按班级clazz分组查询得分80以上的总分数
  8. List<AggregationOperation> operations = new ArrayList<>();
  9. // where
  10. operations.add(Aggregation.match(Criteria.where("score").gte(80)));
  11. // group by [这个求sum]
  12. operations.add(Aggregation.group("clazz").sum("score").as("totleScore"));
  13. // 这个求count
  14. //operations.add(Aggregation.group("clazz").count().as("totleScore"));
  15. // having
  16. //operations.add(Aggregation.match(Criteria.where("totleScore").gt(80)));
  17. Aggregation aggregation = Aggregation.newAggregation(operations);
  18. //查询、并获取结果
  19. AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "student", Document.class);
  20. Document map = results.getRawResults();
  21. System.out.println(map);
  22. }

mapReduce

  1. @Test
  2. public void mapReduce() {
  3. Query query = new Query();
  4. // emit中 key:指定分组的字段;values:要聚合的字段(数组)
  5. String mapFunction = "function() {emit(this.clazz, this.score);}";
  6. // key:分组字段,values:根据key分组之后的值放在一个数组中,这个values就是这个数组
  7. String reduceFunction = "function(key, values) {return Array.sum(values);}";
  8. // 可以对结果做一些处理
  9. MapReduceOptions mapReduceOptions = new MapReduceOptions();
  10. // mapReduceOptions.outputCollection("aaaa"); //生成的结果表(在mongo服务器上可以看到)
  11. // mapReduceOptions.limit(2);
  12. MapReduceResults<Document> results = mongoTemplate.mapReduce(query, "student", mapFunction, reduceFunction, mapReduceOptions, Document.class);
  13. Iterator<Document> it = results.iterator();
  14. for (;it.hasNext();) {
  15. System.out.println(it.next());
  16. }
  17. // 查询每个人的兴趣爱好个数
  18. Query query1 = new Query();
  19. String mapFunction1 = "function() {emit(this.name, this.hobby);}";
  20. String reduceFunction1 = "function(key, values) {" +
  21. "reduceVal = {name: key, hobbys: values};" +
  22. "return reduceVal;" +
  23. "}";
  24. String func_finalize = "function(name, hobbys) {return hobbys.length}";
  25. MapReduceOptions mapReduceOptions1 = new MapReduceOptions();
  26. mapReduceOptions1.finalizeFunction(func_finalize);
  27. MapReduceResults<Document> results1 = mongoTemplate.mapReduce(query1, "student", mapFunction1, reduceFunction1, mapReduceOptions1, Document.class);
  28. for (Iterator<Document> it1 = results1.iterator(); it1.hasNext();) {
  29. System.out.println(it1.next());
  30. }
  31. }

group和mapReduce的区别在于group不能跨片查询,如果是分片集群的话 使用mapReduce

查看mongo拓展的js的Array方法:

  1. > for (var key in Array) {
  2. print(key)
  3. }
  4. contains
  5. unique
  6. shuffle
  7. tojson
  8. fetchRefs
  9. sum
  10. avg
  11. stdDev

分页查询

  1. /**
  2. * 分页查询
  3. */
  4. @Test
  5. public void pageQuery() {
  6. Query query = new Query();
  7. query.skip(1);
  8. query.limit(2);
  9. List<Document> student = mongoTemplate.find(query, Document.class, "student");
  10. System.out.println(student);
  11. }

文件上传

  1. /**
  2. * 文件上传
  3. */
  4. @Test
  5. public void uploadGridFs() throws Exception {
  6. File file = new File("E:\\1.xml");
  7. FileInputStream fin = new FileInputStream(file);
  8. Document doc = new Document();
  9. doc.put("filename", file.getName());
  10. doc.put("uploadDate", new Date());
  11. doc.put("author", "joe");
  12. gridFsTemplate.store(fin, file.getName(), "xml", doc);
  13. }

文件下载

  1. /**
  2. * 文件下载
  3. */
  4. @Test
  5. public void downLoadGridFs() throws Exception {
  6. Query query = new Query();
  7. // query.addCriteria(Criteria.where("filename").is("1.xml"));
  8. query.addCriteria(Criteria.where("metadata.author").is("joe"));
  9. // 1.从fs.files中查询文件的相关信息
  10. GridFSFile gfsFile = gridFsTemplate.findOne(query);
  11. // 2.从fs.chunks中获取文件(通过1中查询的files_id)
  12. GridFsResource resource = gridFsTemplate.getResource(gfsFile);
  13. InputStream in = resource.getInputStream();
  14. FileOutputStream fout = new FileOutputStream(new File("E:\\1bak.xml"));
  15. try {
  16. byte[] buf = new byte[1024];
  17. for (int len;(len = in.read(buf, 0, 1024)) != -1;) {
  18. fout.write(buf, 0, len);
  19. }
  20. fout.flush();
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }

springboot调用mongo的更多相关文章

  1. java springboot调用第三方接口 借助hutoool工具类 爬坑

    楼主是个后端小白一枚,之前没接触过后端,只学了java基本语法,还是在学校老师教的,学的很浅,什么ssh.ssm框架都没有学,最近在自学spring boot,看书学也看不是很懂,就在b站上看教学视频 ...

  2. springboot调用微信的jscode2session报JSONObject异常

    问题背景: 服务器为Centos6.5 JDK:OpenJDK1.7 tomcat7 项目为微信小程序api的后端代码,解密用户信息,代码是采用springboot写的 异常信息: 代码: json异 ...

  3. springboot 调用webservice

    参考:https://www.liangzl.com/get-article-detail-12711.html https://www.cnblogs.com/e206842/p/9047294.h ...

  4. Springboot调用Oracle存储过程的几种方式

    因工作需要将公司SSH项目改为Spingboot项目,将项目中部分需要调用存储过程的部分用entityManagerFactory.unwrap(SessionFactory.class).openS ...

  5. 求助:springboot调用存储过程并使用了pagehelper分页时报错com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

    存储过程如下: dao层的sql Controller层调用: html页面 没有使用pagehelper分页之前,可以正常使用 使用了pagehelper之后就报错 ### Error queryi ...

  6. springboot整合mongo多数据源

    该实例已测试 POM.XML <!-- Spring Boot mongodb 依赖--> <dependency> <groupId>org.springfram ...

  7. springboot集成mongo

    大家可以关注我的微信公众号“秦川以北” 后续更多精彩实用内容分享 ​在项目中配置,mongoDB数据库,spring整合 1. 引入pom依赖 <dependency> <group ...

  8. springboot调用http方式

    1.httpclient 2.okhttp 3.feign 安装Gradle包 compile 'org.springframework.cloud:spring-cloud-starter-open ...

  9. SpringBoot 调用 mysql存储过程的实战

    网络上写的一堆都不能用的 好吧.. 首先创建 存储过程 DROP PROCEDURE IF EXISTS dfsSons; CREATE PROCEDURE dfsSons(IN rootid INT ...

随机推荐

  1. DELPHI给整个项目加编译开关

    DELPHI给整个项目加编译开关 project--options

  2. 解决 screen 连接不上,提示“There is no screen to be resumed matching 18352.” 的问题

    当你挂起screen,下次想重新连上screen时,有时会出现screen session的状态为Attached但是却连不上的情况,比如我想重新进入session id 为18352的screen, ...

  3. GDI+ Image 读取内存二进制流显示图片

    int iBmpSize = cd.nTotleLen; HGLOBAL hMemBmp = GlobalAlloc(GMEM_FIXED, iBmpSize); IStream* pStmBmp = ...

  4. 讲座 - Transposable elements, non-coding RNAs and epigenetic control in embryonic stem cells

    Dr. Andrew Paul HutchinsDepartment of BiologySouthern University of Science and Technology, Shenzhen ...

  5. spring-data-mongodb中的MongoTemplate与MongoRepository及推荐

    SpringData支持两种关系数据存储技术: JDBCJPA ● SpringData 方法定义JPA规范: 1. 不是随便声明的,而需要符合一定的规范2. 查询方法以find | read | g ...

  6. SWLU:主核性能采样、调试工具包

    http://bbs.nsccwx.cn/topic/262/swlu-主核性能采样-调试工具包

  7. 美国gfs数据介绍和解析

    最近有个项目需要开发个气象信息API,可以通过经纬度查找未来几天的气象信息. 经过几天的研究,现在简单总结一下. 1.数据来源数据来源采自美国国家环境预报中心的GFS(全球预报系统),该系统每天发布4 ...

  8. PAT 甲级 1144 The Missing Number (20 分)(简单,最后一个测试点没过由于开的数组没必要大于N)

    1144 The Missing Number (20 分)   Given N integers, you are supposed to find the smallest positive in ...

  9. Sound (audio file) player in java - working source code example

    转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/sound-audio-file-player-in-java-working.html ...

  10. Python第一阶段05

    1.内置方法: 2.Json序列化: import json info = { 'name': 'sisi', } f = open("test.text", "w&qu ...