mongodb 下载官网地址https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.2.12.tgz
解压mongodb
[root@localhost opt]# ls
hazelcast-3.10.2.tar.gz jdk-8u171-linux-x64.tar.gz logstash-6.4.0.tar.gz nginx-1.15.1.tar.gz pcre-8.40.tar.gz zlib-1.2.11 zookeeper-3.4.10.tar.gz
hazelcast-management-center-3.10.1.tar.gz kafka_2.11-1.1.0.tgz mongodb-linux-x86_64-3.2.12.tgz pcre-8.40 redis-4.0.10.tar.gz zlib-1.2.11.tar.gz
[root@localhost opt]# tar zxvf mongodb-linux-x86_64-3.2.12.tgz
将mongodb 移动到你想安装的目录
[root@localhost opt]# mv mongodb-linux-x86_64-3.2.12 /usr/local/mongodb
在mongodb目录下创建日志、数据等存放文件夹
[root@localhost mongodb]# cd /usr/local/mongodb/
[root@localhost mongodb]# mkdir data/db
[root@localhost mongodb]# mkdir logs
[root@localhost mongodb]# ls
bin data GNU-AGPL-3.0 logs MPL-2 README THIRD-PARTY-NOTICES
创建配置文件
[root@localhost mongodb]# cd bin/
[root@localhost bin]# vim mongodb.yml
mongodb.yml
#日志文件存放地址配置
systemLog:
destination: file
path: "/usr/local/mongodb/logs/mongodb.log"
logAppend: true
#数据存放地址配置
storage:
dbPath: "/usr/local/mongodb/data/db"
journal:
enabled: true
#守护进程运行
processManagement:
fork: true
#ip端口绑定
net:
bindIp: 192.168.126.130
port: 27017
更多配置相关信息推荐参考大神的博客 很详细的讲解了每个配置的意义 地址:https://www.cnblogs.com/phpandmysql/p/7763394.html
需要注意的是 请给data\db logs等文件夹相关权限否则启动会报错。
启动mongodb
[root@localhost mongodb]# cd bin/
[root@localhost bin]# vim mongodb.yml
[root@localhost bin]# ls
bsondump mongo mongod mongodb.yml mongodump mongoexport mongofiles mongoimport mongooplog mongoperf mongorestore mongos mongostat mongotop
[root@localhost bin]# ./mongod --config mongodb.yml
通过客户端直接操作mongo
[root@localhost bin]# ls
bsondump mongo mongod mongodb.yml mongodump mongoexport mongofiles mongoimport mongooplog mongoperf mongorestore mongos mongostat mongotop
[root@localhost bin]# ./mongo 192.168.126.130:27017/test
MongoDB shell version: 3.2.12
connecting to: 192.168.126.130:27017/test
Server has startup warnings:
2018-09-18T10:09:47.370+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-09-18T10:09:47.370+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
>
具体的客户端操作命令 请参考其他筒子的博客吧!本文不在详解
下面就是Java代码了,项目使用的是springboot
maven
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-mongodb
org.springframework.boot
spring-boot-starter-web
配置文件
server:
port: 8050
session:
timeout: 10
spring:
data:
mongodb:
uri: mongodb://192.168.126.130:27017/myTest
创建实体映射类
package com.cloud.mongodb.po;
/**
* @author zane
*
*/
public class UserPo {
private Long userId;
private String userName;
private String userNickName;
private Integer userAge;
private Integer userSex;
private String email;
private String phone;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserNickName() {
return userNickName;
}
public void setUserNickName(String userNickName) {
this.userNickName = userNickName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public Integer getUserSex() {
return userSex;
}
public void setUserSex(Integer userSex) {
this.userSex = userSex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public UserPo(Long userId, String userName, String userNickName, Integer userAge, Integer userSex, String email,
String phone) {
super();
this.userId = userId;
this.userName = userName;
this.userNickName = userNickName;
this.userAge = userAge;
this.userSex = userSex;
this.email = email;
this.phone = phone;
}
public UserPo() {
super();
}
@Override
public String toString() {
return new StringBuffer("userId:").append(this.userId).append(" userName:").append(this.userName)
.append(" userNickName:").append(this.userNickName).append(" userAge:").append(this.userAge)
.append(" userSex:").append(this.userSex).append(" email:").append(this.email).append(" phone:")
.append(this.phone).toString();
}
}
创建mongo数据操作类、接口 这里有两种实现方式 使用MongoRepository 和MongoTemplate
继承MongoRepository:
@Component
public interface UserRepository extends MongoRepository {
/*
* MongoRepository与HibernateTemplete相似,提供一些基本的方法,
* 实现的方法有findone(),save(),count(),findAll(),findAll(Pageable),delete(),deleteAll
* ()..etc 要使用Repository的功能,先继承MongoRepository接口
* 其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。
* 之后在spring-boot中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。 starter-data-mongodb
* 支持方法命名约定查询 findBy{User的name属性名}, findBy后面的属性名一定要在User类中存在,否则会报错
*/
/**
* 通过手机号查询
*
* @param phone
* @return
*/
public List findByPhone(String phone);
}
使用MongoTemplate
package com.cloud.mongodb.mongo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import com.cloud.mongodb.po.UserPo;
@Component
public class UserDao {
@Autowired
private MongoTemplate mongoTemplate;
public void save(UserPo user) {
mongoTemplate.save(user);
}
}
两种方式的优缺点:
MongoRepository:
它其实就是继承Repository 的子接口 ,Repository 是 Spring Data 的一个核心接口。使用它可以使你不用写相关的查询组合语句,它会内部为我们实现这样的一个类。只要你按规定定义好接口名就可以免去你写查询组合语句。相关详细介绍的博客地址:https://blog.csdn.net/qinsihang/article/details/19921981
MongoTemplate:
MongoTemplate是数据库和代码之间的接口,它有两个核心的类:Criteria类:封装所有的语句,以方法的形式查询、Query类:将语句进行封装或者添加排序之类的操作。
MongoRepository的缺点是不够灵活,MongoTemplate 正好可以弥补
执行测试:
package com.cloud.mongodb;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.cloud.mongodb.mongo.dao.UserDao;
import com.cloud.mongodb.mongo.repository.UserRepository;
import com.cloud.mongodb.po.UserPo;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AppTest {
@Autowired
private UserDao dao;
@Autowired
private UserRepository repository;
@Test
public void test1() {
UserPo user = new UserPo();
user.setUserId(2L);
user.setUserName("张三");
user.setUserNickName("老张");
user.setUserAge(33);
user.setPhone("15555555225");
user.setUserSex(1);
user.setEmail("[email protected]");
dao.save(user);
}
@Test
public void test2() {
List list = repository.findByPhone("15555555225");
if (null != list && !list.isEmpty()) {
for (UserPo userPo : list) {
System.out.println(userPo.toString());
}
}
}
}
执行结果
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE)
2018-09-18 11:26:00.925 INFO 10704 --- [ main] com.cloud.mongodb.AppTest : Starting AppTest on DESKTOP-R7GPPNQ with PID 10704 (started by zane in E:\workSpace\learn-project\cloud-mongodb)
2018-09-18 11:26:00.925 INFO 10704 --- [ main] com.cloud.mongodb.AppTest : No active profile set, falling back to default profiles: default
2018-09-18 11:26:00.957 INFO 10704 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@56cdfb3b: startup date [Tue Sep 18 11:26:00 CST 2018]; root of context hierarchy
2018-09-18 11:26:02.903 INFO 10704 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[192.168.126.130:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-09-18 11:26:02.980 INFO 10704 --- [8.126.130:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:6}] to 192.168.126.130:27017
2018-09-18 11:26:02.981 INFO 10704 --- [8.126.130:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=192.168.126.130:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 12]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=652533}
2018-09-18 11:26:03.615 INFO 10704 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@56cdfb3b: startup date [Tue Sep 18 11:26:00 CST 2018]; root of context hierarchy
2018-09-18 11:26:03.674 INFO 10704 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-09-18 11:26:03.676 INFO 10704 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-09-18 11:26:03.701 INFO 10704 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-18 11:26:03.701 INFO 10704 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-18 11:26:03.730 INFO 10704 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-18 11:26:03.871 INFO 10704 --- [ main] com.cloud.mongodb.AppTest : Started AppTest in 3.242 seconds (JVM running for 3.787)
2018-09-18 11:26:03.950 INFO 10704 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:7}] to 192.168.126.130:27017
userId:2 userName:张三 userNickName:老张 userAge:33 userSex:1 email:[email protected] phone:15555555225
2018-09-18 11:26:04.035 INFO 10704 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@56cdfb3b: startup date [Tue Sep 18 11:26:00 CST 2018]; root of context hierarchy
2018-09-18 11:26:04.039 INFO 10704 --- [ Thread-2] org.mongodb.driver.connection : Closed connection [connectionId{localValue:2, serverValue:7}] to 192.168.126.130:27017 because the pool has been closed.
客户端查询:
[root@localhost bin]# ./mongo 192.168.126.130:27017/test
MongoDB shell version: 3.2.12
connecting to: 192.168.126.130:27017/test
Server has startup warnings:
2018-09-18T10:09:47.370+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-09-18T10:09:47.370+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-09-18T10:09:47.371+0800 I CONTROL [initandlisten]
> show dbs
local 0.000GB
myTest 0.000GB
> use myTest
switched to db myTest
> db.userPo.find({phone:'15555555225'})
{ "_id" : ObjectId("5ba0704b12a2a229d031e8cd"), "_class" : "com.cloud.mongodb.po.UserPo", "userId" : NumberLong(2), "userName" : "张三", "userNickName" : "老张", "userAge" : 33, "userSex" : 1, "email" : "[email protected]", "phone" : "15555555225" }