一、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. 1103 Integer Factorization

    题意:给出一个正整数N,以及k,p,要求把N分解成k个因式,即N=n1^p + n2^p + ... + nk^p.要求n1,n2,...按降序排列,若有多个解,则选择n1+n2+...+nk最大的, ...

  2. 列表:list[1],切片list[1:3],追加insert,修改,删除remove,del,pop,查找index,统计count,清空list.clear() 翻转list.reverse(),排序list.sort(),扩展list.extend,

    列表的定义: 列表的使用以及取值:用逗号的方式,取列表两个值,会打印出2个项目,两个项目之间自动有一个空格. 如果想取中间几个值: 请注意,如果取值1和2,那么要写[1,3],要记住这里是顾头不顾尾. ...

  3. Fiddler移动端抓包

    有关手机抓包之前没有接触过,实际工作用到的不多,因此学了也就忘了. 来了新公司之后,产品主要以移动端为主,抓取线上线下包便成了平常之事,一些开发也会来请教如何在手机上抓包. 回归正题,抓取移动端包有很 ...

  4. java后台读取配置文件中key与value -----demo

    public class ResourcesUtils { /* * @description:根据属性获取文件名 * * @param:propertyName文件的属性名 * * @return: ...

  5. redis改密码

    一. 如何初始化redis的密码? 总共2个步骤: a.在配置文件中有个参数: requirepass  这个就是配置redis访问密码的参数. 比如 requirepass test123 b.配置 ...

  6. 十年Java架构师分享

    看到一篇十年java架构师分享需要掌握的技术点,有时间对照一下,好好学习一下. ------------------------------------------------------------ ...

  7. 29_java之JDBC|SQL注入

    01JDBC概念和数据库驱动程序 * A: JDBC概念和数据库驱动程序 * a: JDBC概述 * JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执 ...

  8. 四、jenkins+postman+newman环境搭建

    前提: 搭建环境之前需要先理清楚各个环境的依赖关系,jenkins只支持windows命令行跟linux shell环境执行构建命令,而postman的测试脚本不能直接在命令行或shell环境执行,p ...

  9. 异步编程之co——源码分析

    异步编程系列教程: (翻译)异步编程之Promise(1)--初见魅力 异步编程之Promise(2):探究原理 异步编程之Promise(3):拓展进阶 异步编程之Generator(1)--领略魅 ...

  10. leetcode747

    public class Solution { public int DominantIndex(int[] nums) { var list = new List<KeyValuePair&l ...