创建文件夹
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
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
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
#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
@Document("collection1")
@Data
public class People implements Serializable {
@Id
private String id;
@Field("name")
private String userName;
private Integer age;
}
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);
}
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;
}
}
@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());
}
@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);
}