Mongodb学习

安装教程

window 二进制安装

创建文件夹
data/db
创建配置文件:mongod.conf

storage:
  dbPath: F:\Java\app\mongodb-win32-x86_64-2008plus-ssl-4.0.12\data

启动

.\bin\mongod.exe -f .\config\mongod.conf

Mongodb学习_第1张图片

Linux安装

Mongodb学习_第2张图片

mkdir -p data/db
mkdir -p logs

编写配置文件:mongodb.conf

#增加如下配置
dbpath = /usr/local/mongodb/data/db #数据文件存放目录
logpath = /usr/local/mongodb/logs/mongodb.log #日志文件存放目录
port = 27017  #端口
bind_ip = 0.0.0.0
fork = true  #以守护程序的方式启用,即在后台运行

启动mongodb

 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf

使用教程

# 查看版本
db.version()
# 查看所有数据库
show dbs;
# 使用数据库
use admin;
# 查看当前数据库
db
# 关闭mongodb
db.shutdownServer() 

创建一个articletest数据库,并赋予全部权限

use articletest;
# 插入一条数据
db.comment.insert({"articleId":"10000","content":"今天天气真好!","userId":"10001"})
# 切换到admin数据库
use admin;
# 查看当前用户zkc 没有
show users;
# 创建新的用户
db.createUser({user:"root",pwd:"A_dminjs#888",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
db.createUser({user:"testuser",pwd:"123456",roles:[{role:"readWrite",db:"admin"}]})
# 修改用户
db.updateUser("testuser", {"roles":[{"role":"userAdminAnyDatabase",db:"admin"}
# 更新密码
db.updateUser("用户名", {"pwd":"新密码"})
db.changeUserPassword("用户名", "新密码")
# 删除用户
db.dropUser("testuser") 
#验证是否有该用户
db.auth("testuser", "123456")

登录

mongo
mongo IP:27017/admin -uroot -pA_dminjs#888

Mongodb学习_第3张图片

Java程序调用mongodb

pom.xml


        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>

配置文件 application.properties

#Mongodb数据源
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=root
spring.data.mongodb.password=A_dminjs#888
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=articledb

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

创建pojo People

@Document("collection1")
@Data
public class People implements Serializable {

    @Id
    private String id;

    @Field("name")
    private String userName;

    private Integer age;
}

MongoService

import java.util.List;

public interface MongoService {
    //添加数据
    public Boolean save(People people);
    //根据id查询
    public People getById(String id);
    //查询全部
    public List<People> getAll();
    //修改数据
    public Boolean update(String id);
}

MongoServiceImpl

package com.shengun.mongo.service.impl;

import com.shengun.mongo.pojo.People;
import com.shengun.mongo.service.MongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MongoServiceImpl implements MongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Override
    public Boolean save(People people) {
        People save = mongoTemplate.save(people);
        if(save == null){
            return false;
        }
        return true;
    }

    @Override
    public People getById(String id) {
        People people = mongoTemplate.findById(id, People.class);
        return people;
    }

    @Override
    public List<People> getAll() {
        List<People> list = mongoTemplate.findAll(People.class);
        return list;
    }

    @Override
    public Boolean update(String id) {
        People people = mongoTemplate.findById(id, People.class);
        if(people != null){
            people.setAge(200);
            People save = mongoTemplate.save(people);
            if(save == null){
                return false;
            }
        }
        return true;
    }
}

MongoController

添加数据

    @GetMapping("/add")
    public R add(){
        People people = new People();
        people.setUserName("张三");
        people.setAge(19);
        Boolean save = mongoService.save(people);
        return R.ok().data("flag", save);
    }

更新数据

    @GetMapping("/update/{id}")
    public R update(@PathVariable String id){
        Boolean update = mongoService.update(id);
        return R.ok().data("flag", update);
    }

删除数据

    @GetMapping("/delete/{id}")
    public R delete(@PathVariable String id){
        People people = new People();
        people.setId(id);
        DeleteResult remove = mongoTemplate.remove(people);
        return R.ok().data("data", remove);
    }

根据年龄查询 数据

    @GetMapping("/getByAge/{age}")
    public R getByAge(@PathVariable Integer age){
        Query query = new Query(Criteria.where("age").gte(age));
        List<People> list = mongoTemplate.find(query, People.class);
        return R.ok().data("data", list);
    }

得到所有数据

    @GetMapping("/getList")
    public R select(){
        List<People> all = mongoService.getAll();
        return R.ok().data("list", all);
    }

存储图片和文件

 @Autowired
    private GridFsTemplate gridFsTemplate;
 @PostMapping("/upload")
    public R upload(MultipartFile file) throws Exception{
        log.info("############上传开始#############");
        if(file == null){
            return R.error().message("未上传文件");
        }
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String contentType = file.getContentType();
        ObjectId store = gridFsTemplate.store(inputStream, originalFilename, contentType);
        log.info("############id####:" + store);
        log.info("############id####:" + store.toHexString());
        return R.ok().data("id", store.toHexString());
    }

获取图片

    @GetMapping("/showing/{imgeId}")
    public void showImage(@PathVariable String imgeId, HttpServletResponse response) throws IOException {
        log.info("##############查询id:" + imgeId);
        Query id = new Query(Criteria.where("_id").is(imgeId));
        GridFSFile result  = gridFsTemplate.findOne(id);
        GridFsResource resource = gridFsTemplate.getResource(result);
        InputStream inputStream = resource.getInputStream();
        response.setContentType("image/jpg");
        IOUtils.copy(inputStream,response.getOutputStream());
    }

获取pdf

    @GetMapping("/showPdf/{pdfId}")
    public void showPdf(@PathVariable String pdfId, HttpServletResponse response) throws IOException {
        log.info("##############查询id:" + pdfId);
        Query id = new Query(Criteria.where("_id").is(pdfId));
        GridFSFile result  = gridFsTemplate.findOne(id);
        GridFsResource resource = gridFsTemplate.getResource(result);
        InputStream inputStream = resource.getInputStream();
//        response.setContentType("image/jpg");
//        response.setContentType("text/html");
        response.setContentType("application/pdf");
        IOUtils.copy(inputStream,response.getOutputStream());
    }

根据大于并且小于查询

void range() { 
 Query query = new Query(Criteria.where("age").gte(12).lte(14)); 
 List<People> list = mongoTemplate.find(query, People.class); 
 list.forEach(System.out::println); 
} 

根据正则查询(模糊查询)

void regex() { 
 // java中正则不需要有// 
 Query query = new Query(Criteria.where("name").regex("张")); 
 List<People> list = mongoTemplate.find(query, People.class); 
 list.forEach(System.out::println); 
} 

多添加查询

@Test 
void and() { 
 Criteria c = new Criteria(); 
 c.andOperator(Criteria.where("name").is("张三123"), Criteria.where("age").is(12)); 
 Query query = new Query(c); 
 List<People> list = mongoTemplate.find(query, People.class); 
 list.forEach(System.out::println); 
}

你可能感兴趣的:(中间件,mongodb)