springboot+mongonDB

一、mongonDB基本介绍

什么是MongoDB ?

MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。

在高负载的情况下,添加更多的节点,可以保证服务器性能。

MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

 

主要特点

  • MongoDB的提供了一个面向文档存储,操作起来比较简单和容易。
  • 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。
  • 你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。
  • 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。
  • Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
  • MongoDb 使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。
  • Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。
  • Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录,将key与value传给Reduce函数进行处理。
  • Map函数和Reduce函数是使用Javascript编写的,并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。
  • GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。
  • MongoDB允许在服务端执行脚本,可以用Javascript编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。
  • MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。
  • MongoDB安装简单。

一、java操作mongonDB示例

1、新建maven工程springboot-mongodb,工程结构如下:

2、引入springboot和mongodb的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springboot.mongodb</groupId>
  <artifactId>springboot-mongodb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-mongodb</name>
  <description>springboot-mongodb</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
  </parent>
    <dependencies>
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
     </dependency>
  </dependencies>
</project>

3、建立springboot主类

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

4、在src/main/resource下添加mongodb的数源据配置application.yml

spring:
  data:
    mongodb:
      uri: mongodb://hzb:hzb@172.16.63.208:27017/hzb_test?readPreference=secondaryPreferred

数据库名 hzb_test  ,用户hzb,密码hzb

5、实体类

Student:

package com.springboot.model;

public class Student {
        private String name;
        private String sex;
        private Integer age;
        private String des;
        private StudentScore studentScore;
        
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public StudentScore getStudentScore() {
            return studentScore;
        }
        public void setStudentScore(StudentScore studentScore) {
            this.studentScore = studentScore;
        }
        public String getDes() {
            return des;
        }
        public void setDes(String des) {
            this.des = des;
        }
}

StudentScore:

package com.springboot.model;

public class StudentScore {
        private String chinese;
        private String english;
        private String des;
        public String getChinese() {
            return chinese;
        }
        public void setChinese(String chinese) {
            this.chinese = chinese;
        }
        public String getEnglish() {
            return english;
        }
        public void setEnglish(String english) {
            this.english = english;
        }
        public String getDes() {
            return des;
        }
        public void setDes(String des) {
            this.des = des;
        }
}

6、操作mongondb的dao

package com.springboot.dao;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;

import com.springboot.model.Student;

@Component
public class StudentDao{
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    /**
     * 保存一个Student信息到student集合里
     * @param stu
     */
    public void save(Student stu){
        try {
            mongoTemplate.save(stu,"student");
        } catch (Exception e) {
            // TODO: handle exception
        }    
    }
    
    /**
     * 查询所有的Student信息
     * @return
     */
    public List<Student> findAll(){
        return mongoTemplate.findAll(Student.class,"student");
    }
    
    /**
     * 通过Student.name查询document
     * @param name
     * @return
     */
    public List<Student> findByName(String name){
        List<Student> list=null;
        try {
            Query query=new Query(Criteria.where("name").is(name));
            list=mongoTemplate.find(query, Student.class,"student");
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
    
    /**
     * 通过Student.StudentScore.des查询document
     * @param des
     * @return
     */
    public List<Student> findByStudentScoreDes(String des){
        List<Student> list=null;
        try {
            Query query=new Query(Criteria.where("studentScore.des").is(des));
            list=mongoTemplate.find(query, Student.class,"student");
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
    
    
    /**
     * 通过Student.name和Student.des查询document
     *  @param name
     * @param des
     * @return
     */
    public List<Student> searchByNameAndDes(String name,String des){
        List<Student> list=null;
        try {
            Query query=new Query(Criteria.where("name").is(name).and("des").is(des));
            list=mongoTemplate.find(query, Student.class,"student");
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
    
    /**
     * 通过Student.name和Student.Student.des查询document
     *  @param name
     * @param des
     * @return
     */
    public List<Student> searchByNameAndStudentScoreDes(String name,String des){
        List<Student> list=null;
        try {
            Query query=new Query(Criteria.where("name").is(name).and("studentScore.des").is(des));
            list=mongoTemplate.find(query, Student.class,"student");
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
    
    /**
     * 更新
     * @param stu
     */
    public void update(Student stu){
        try {
            Query query=new Query(Criteria.where("name").is(stu.getName()));
            Update update= new Update().set("des", stu.getDes()).set("studentScore.des", stu.getStudentScore().getDes());
            //更新查询返回结果集的第一条
            mongoTemplate.updateFirst(query,update,Student.class,"student");
            //更新查询返回结果集的所有
            // mongoTemplate.updateMulti(query,update,Student.class);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    
    /**
     * 删除
     * @param name
     */
    public void remove(String name){
        Query query=new Query(Criteria.where("name").is(name));
        mongoTemplate.remove(query, Student.class,"student");
    }
}

7、controller

package com.springboot.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.dao.StudentDao;
import com.springboot.model.Student;
import com.springboot.model.StudentScore;

@RestController
@RequestMapping("/mongo")
public class StudentController {
    
    @Autowired
    private StudentDao studentDao;
    

    
    /**
     * 向mongondb添加一个document对象
     */
    @PostMapping("/add")
    public void add() {
        Student student=new Student();
        student.setName("hzb");
        student.setSex("man");
        student.setAge(31);      
        student.setDes("hzb_father");
        StudentScore score=new StudentScore();
        score.setChinese("88");
        score.setEnglish("93");  
        score.setDes("hzb_child");  
        student.setStudentScore(score);
        
        Student student1=new Student();
        student1.setName("xiaweihu");
        student1.setSex("man");
        student1.setAge(31);      
        student1.setDes("xiaweihu_father");
        StudentScore score1=new StudentScore();
        score1.setChinese("66");
        score1.setEnglish("54");  
        score1.setDes("xiaweihu_child");  
        student1.setStudentScore(score1);
        
        Student student2=new Student();
        student2.setName("hzb");
        student2.setSex("man");
        student2.setAge(31);      
        student2.setDes("hzb_father");
        StudentScore score2=new StudentScore();
        score2.setChinese("77");
        score2.setEnglish("99");  
        score2.setDes("hzb_child2");  
        student2.setStudentScore(score2);      
        studentDao.save(student);      
        studentDao.save(student1);
        studentDao.save(student2);
    }
    
    /**
     * 查询mongodb当中的所有document
     * @return
     */
    @GetMapping("/findAll")
    public List<Student> findAll() {
        List<Student> list= studentDao.findAll();
        return list;
    }
    /**
     * 通过名字查询document
     * @return
     */
    @GetMapping("/findByName")
    public List<Student> findByName() {
        List<Student> student=studentDao.findByName("hzb");
        return student;
    }
    

  
    /**
     * 通过Student.Student.des查询document
     * @param des
     * @return
     */
    @GetMapping("/findByStudentScoreDes")
    public List<Student> findByStudentScore_Des(String des){
        List<Student> student=studentDao.findByStudentScoreDes("hzb_child2");
        return student;
    }
    
    /**
     * 通过Student.name和Student.des查询document
     * @param des
     * @return
     */
    @GetMapping("/findByNameAndDes")
    public List<Student> findByNameAndDes(String des){
        List<Student> student=studentDao.searchByNameAndDes("hzb","hzb_father");
        return student;
    }
    
    /**
     * 通过Student.name和Student.Student.des查询document
     * @param des
     * @return
     */
    @GetMapping("/findByNameAndStudentScoreDes")
    public List<Student> findByNameAndStudentScoreDes(String des){
        List<Student> student=studentDao.searchByNameAndStudentScoreDes("hzb","hzb_child2");
        return student;
    }
    
    /**
     * 更新document
     */
    @PutMapping("/updateByName")
    public void ubdateByName(){
        List<Student> students=studentDao.findByName("xiaweihu");
        Student student=students.get(0);
        student.setDes("aaaaaaaaaaaaaaaaaaaa");
        student.getStudentScore().setDes("bbbbbbbbbbbbbbbbbbbbb");
        studentDao.update(student);
    }
    
    /**
     * 删除document
     */
    @DeleteMapping("/deleteByName")
    public void deleteByName(){
        studentDao.remove("xiaweihu");
    }
    
}

7、运行结果

1)当执行   http://localhost:8080/mongo/add

用Robomongo 1.0查看mongodb数据库,可以看到插入了三条记录

/* 1 */
{
    "_id" : ObjectId("5922792f48a5d132a48886f2"),
    "_class" : "com.springboot.model.Student",
    "name" : "hzb",
    "sex" : "man",
    "age" : 31,
    "des" : "hzb_father",
    "studentScore" : {
        "chinese" : "88",
        "english" : "93",
        "des" : "hzb_child"
    }
}

/* 2 */
{
    "_id" : ObjectId("5922792f48a5d132a48886f3"),
    "_class" : "com.springboot.model.Student",
    "name" : "xiaweihu",
    "sex" : "man",
    "age" : 31,
    "des" : "xiaweihu_father",
    "studentScore" : {
        "chinese" : "66",
        "english" : "54",
        "des" : "xiaweihu_child"
    }
}

/* 3 */
{
    "_id" : ObjectId("5922792f48a5d132a48886f4"),
    "_class" : "com.springboot.model.Student",
    "name" : "hzb",
    "sex" : "man",
    "age" : 31,
    "des" : "hzb_father",
    "studentScore" : {
        "chinese" : "77",
        "english" : "99",
        "des" : "hzb_child2"
    }
}

2)查询所有的Student记录,http://localhost:8080/mongo/add

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "88",
      "english": "93",
      "des": "hzb_child"
    }
  },
  {
    "name": "xiaweihu",
    "sex": "man",
    "age": 31,
    "des": "xiaweihu_father",
    "studentScore": {
      "chinese": "66",
      "english": "54",
      "des": "xiaweihu_child"
    }
  },
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

3)查询名字为“hzb”的Student记录,http://localhost:8080/mongo/findByName

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "88",
      "english": "93",
      "des": "hzb_child"
    }
  },
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

4)查询名字为studentScore.des为hzb_child2的Student记录,http://localhost:8080/mongo/findByStudentScoreDes

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

5)查询名字为name为hzb,des为hzb_father的Student记录,http://localhost:8080/mongo/findByNameAndDes

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "88",
      "english": "93",
      "des": "hzb_child"
    }
  },
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

6)查询名字为name为hzb,studentScore.des为hzb_child2的Student记录,http://localhost:8080/mongo/findByNameAndStudentScoreDes

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

7)执行http://localhost:8080/mongo/updateByName后再执行http://localhost:8080/mongo/findAll

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "88",
      "english": "93",
      "des": "hzb_child"
    }
  },
  {
    "name": "xiaweihu",
    "sex": "man",
    "age": 31,
    "des": "aaaaaaaaaaaaaaaaaaaa",
    "studentScore": {
      "chinese": "66",
      "english": "54",
      "des": "bbbbbbbbbbbbbbbbbbbbb"
    }
  },
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]

8)执行http://localhost:8080/mongo/deleteByName后再执行http://localhost:8080/mongo/findAll

[
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "88",
      "english": "93",
      "des": "hzb_child"
    }
  },
  {
    "name": "hzb",
    "sex": "man",
    "age": 31,
    "des": "hzb_father",
    "studentScore": {
      "chinese": "77",
      "english": "99",
      "des": "hzb_child2"
    }
  }
]
原文地址:https://www.cnblogs.com/boshen-hzb/p/6879604.html