一、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.</modelVersion>
<groupId>com.springboot.mongodb</groupId>
<artifactId>springboot-mongodb</artifactId>
<version>0.0.-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..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"
}
}
]

springboot+mongonDB的更多相关文章

  1. 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用

    问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...

  2. 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo

    Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...

  3. Springboot搭建web项目

    最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了.关于springboot相关的介绍我就不赘述了,大家自行百度google. 一.pom配置 首先,建立一个maven项目,修 ...

  4. Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)

    这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...

  5. 解决 SpringBoot 没有主清单属性

    问题:SpringBoot打包成jar后运行提示没有主清单属性 解决:补全maven中的bulid信息 <plugin> <groupId>org.springframewor ...

  6. SpringBoot中yaml配置对象

    转载请在页首注明作者与出处 一:前言 YAML可以代替传统的xx.properties文件,但是它支持声明map,数组,list,字符串,boolean值,数值,NULL,日期,基本满足开发过程中的所 ...

  7. springboot 学习资源推荐

    springboot 是什么?对于构建生产就绪的Spring应用程序有一个看法. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.(这是springboot的官方介绍) 我们为什么要学 ...

  8. Springboot框架

    本片文章主要分享一下,Springboot框架为什么那么受欢迎以及如何搭建一个Springboot框架. 我们先了解一下Springboot是个什么东西,它是干什么用的.我是刚开始接触,查了很多资料, ...

  9. 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧

    做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...

随机推荐

  1. ESXI5-WIN2008R2安装域控以及额外域笔记

    每次安装域控都要找教程,每次都没法一次性搞定.写个笔记吧...主要是给自己看的.写的比较含糊.不清楚的可以直接QQ本人. 1.安装WIN2008R2,192.168.188.10 2.上载SLICET ...

  2. HttpClient基础用法

    一.HttpClient HttpClient是Apache HttpComponents 下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包(httpclient-4. ...

  3. VC6.0打开文件是卡死的解决办法

    删除工程目录下的 .ncb .opt 文件,然后就OK了!

  4. php对业务平台接口调用的封装格式

    1.封装类示例:E:\html\pim\php_mcloud_cas\util\UmcPlatform.class.php <?php class Util_UmcPlatform{ const ...

  5. django之使用jquery完成ajax

    使用Ajax 使用视图通过上下文向模板中传递数据,需要先加载完成模板的静态页面,再执行模型代码,生成最张的html,返回给浏览器,这个过程将页面与数据集成到了一起,扩展性差 改进方案:通过ajax的方 ...

  6. question?

  7. python学习——练习题(8)

    """ 题目:输出 9*9 乘法口诀表. """ def answer1(): """ 自己用最普通的双重循环 ...

  8. leetcode384

    public class Solution { private int[] nums; private Random random; public Solution(int[] nums) { thi ...

  9. views获取数据 -- request包含的方法

    request.GET request.POST request.FILES request.path_info request.xxx.getlist request.method request. ...

  10. Python 多进程使用

    进程通信 方式一.共享内存(进程安全,效率高) 共享变量:multiprocessing.Value 共享数组:multiprocessing.Array   方式二.Manager对象:list, ...