mongodb 速成笔记

以下环境为mac osx + jdk 1.8 + mongodb v3.2.3

一、安装

brew安装方式是mac下最简单的方式

1
2
brew update
brew  install  mongodb

其它OS上的安装请参考:https://docs.mongodb.org/manual/installation/

 

二、启动

2.1 最基本的启动

1
mongod

 不加任何参数时,db默认保存在/data/db目录(如果该目录不存在,启动会报错),监听的端口是27017,且不启动安全认证机制(即:谁都可以连接,只要连接上来的用户都是管理员)

2.2 指定dbpath

1
mongod --dbpath ~ /data/db/mongo

指定dbpath后,数据文件将保存在指定的目录下(注意:该目录必须有读写权限)

2.3 指定端口

1
mongod --dbpath ~ /data/db/mongo  --port 12345

2.4 启用安全认证

1
mongod --dbpath ~ /data/db/mongo  --port 12345 --auth

这个下面还会仔细讲解,这里只要记得有--auth这个选项即可。

2.5 其它一些选项

1
mongod --help

如果想详细了解所有启动选项,可以加--help查看所有可选参数。

启动成功后,可以用 mongo 命令来连接

1
2
3
4
➜  ~ mongo
MongoDB shell version: 3.2.4
connecting to:  test
>

然后就可以直接使用各种命令来操作db了 

 

三、安全相关

不带--auth的启动方式是很可怕的,没有任何安全控制,一般只限于开发环境。生产环境肯定要开启安全认证,mongodb在安全认证的主要思路是:

先在某个库上创建用户(db.createUser) -> 将该用户授权(db.auth) -> mongod启动时指定--auth选项 -> mongo客户端连接时指定用户名、密码、认证db(或者连接时先不指定用户名、密码,连接上以后,再用db.auth切换到认证用户身份)

3.0 创建数据库

1
use mydb

跟mysql差不多,use 后加数据库名称即可,如果数据库不存在,会自动创建。假设以下的所有安全相关的操作,都是在mydb这个库下。

3.1 创建用户

切换到相对的db后,使用下面的命令创建用户

1
2
3
db.createUser( {  "user"  "admin" ,
                  "pwd" "123456" ,              
                  "roles"  : [  "readWrite" , "dbAdmin" , "userAdmin" ]})

这样就创建了一个名为admin的管理员,而且具备读写、db管理、用户管理权限。如果想知道mongo默认有哪些roles角色,可参考:https://docs.mongodb.org/manual/reference/built-in-roles/#built-in-roles

3.2 授权

1
2
3
4
db.auth({
    user:  "admin" ,
    pwd "123456"
}) 

3.3 用--auth 重启mongod

1
mongod --auth

3.4 客户端连接时,指定安全信息

1
mongo localhost:27017 /mydb  -u admin -p 123456 --authenticationDatabase mydb

大家参考上面的命令修改相关参数(比如:端口号之类的),连接上去后,可以尝试

1
db.orders.insert({ 'orderId' :1, 'productName' : 'iphone' })

 看看能否写入数据。

注:作为对比,大家还可以创建一个其它只有read权限的用户(比如:guest/guest),同样的姿势连接上去,再insert试试,正常情况话,应该写入失败。

安全相关的更详细信息,请参考 :https://docs.mongodb.org/manual/core/authentication/

 

四、CRUD操作

一般教程上都是讲解如果在mongo终端下使用命令来做CRUD,但是更多情况下,我们是在代码里完成这些操作的,所以下面说下如何利用spring-data-mongo来操作mongo,以gradle项目为例,下面的代码参考了spring官方的示例代码

4.1 build.gradle文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
group  'com.cnblogs.yjmyzz'
version  '1.0-SNAPSHOT'
 
apply plugin:  'java'
apply plugin:  'application'
apply plugin:  'spring-boot'
 
sourceCompatibility = 1.8
 
buildscript {
     repositories {
         maven {
             url  'http://maven.oschina.net/content/groups/public/'
         }
     }
 
     dependencies {
         classpath( "org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE" )
     }
}
 
repositories {
     maven {
         url  'http://maven.oschina.net/content/groups/public/'
     }
}
 
dependencies {
     compile  'org.springframework.data:spring-data-mongodb:1.8.4.RELEASE'
     compile( "org.springframework.boot:spring-boot-starter-actuator" )
     testCompile group:  'junit' , name:  'junit' , version:  '4.12'
}
 
mainClassName =  'com.cnblogs.yjmyzz.mongo.Application'

 其实关键的只有一行:

1
compile  'org.springframework.data:spring-data-mongodb:1.8.4.RELEASE'

4.2 spring配置文件

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
 5        xsi:schemaLocation=
 6                "http://www.springframework.org/schema/data/mongo
 7           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
 8           http://www.springframework.org/schema/beans
 9           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
10 
11     <mongo:db-factory id="mongoDbFactory"
12                       host="localhost"
13                       port="27017"
14                       dbname="yjmyzz"
15                       username="admin"
16                       password="123456"/>
17 
18     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
19         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
20     </bean>
21 
22 </beans>
复制代码

4.3 定义Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package  com.cnblogs.yjmyzz.mongo.model;
 
import  org.springframework.data.annotation.Id;
 
 
public  class  Customer {
 
     @Id
     private  String id;
 
     private  String firstName;
     private  String lastName;
 
     public  Customer() {}
 
     public  Customer(String firstName, String lastName) {
         this .firstName = firstName;
         this .lastName = lastName;
     }
 
     @Override
     public  String toString() {
         return  "Customer{"  +
                 "id='"  + id + '\ ''  +
                 ", firstName='"  + firstName + '\ ''  +
                 ", lastName='"  + lastName + '\ ''  +
                 '}' ;
     }
 
     public  String getId() {
         return  id;
     }
 
     public  void  setId(String id) {
         this .id = id;
     }
 
     public  String getFirstName() {
         return  firstName;
     }
 
     public  void  setFirstName(String firstName) {
         this .firstName = firstName;
     }
 
     public  String getLastName() {
         return  lastName;
     }
 
     public  void  setLastName(String lastName) {
         this .lastName = lastName;
     }
}

4.4 定义DAO接口

这里有一些默认的约定要理解,比如上面的findByLastName这个方法,执行时会自动按Customer的lastName属性来find数据。更详细的方法名与类属性的默认约定,可参考:http://docs.spring.io/spring-data/data-mongo/docs/1.8.4.RELEASE/reference/html/

4.5 Application使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package  com.cnblogs.yjmyzz.mongo;
 
import  com.cnblogs.yjmyzz.mongo.model.Customer;
import  com.cnblogs.yjmyzz.mongo.repository.CustomerRepository;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.beans.factory.annotation.Configurable;
import  org.springframework.boot.CommandLineRunner;
import  org.springframework.boot.SpringApplication;
import  org.springframework.boot.autoconfigure.SpringBootApplication;
import  org.springframework.context.annotation.ImportResource;
import  org.springframework.data.domain.Page;
import  org.springframework.data.domain.PageRequest;
import  org.springframework.data.mongodb.core.MongoTemplate;
import  org.springframework.data.mongodb.core.query.Criteria;
import  org.springframework.data.mongodb.core.query.Query;
 
import  java.util.List;
 
@Configurable ()
@SpringBootApplication
@ImportResource ( "classpath:spring-context.xml" )
public  class  Application  implements  CommandLineRunner {
 
     @Autowired
     private  CustomerRepository repository;
 
     @Autowired
     MongoTemplate mongoTemplate;
 
     public  static  void  main(String[] args) {
 
         SpringApplication.run(Application. class , args);
 
//        ApplicationContext ctx = SpringApplication.run(Application.class, args);
//
//        System.out.println("getBeanDefinitionNames ==> ");
//        for (String beanName : ctx.getBeanDefinitionNames()) {
//            System.out.println(beanName);
//        }
//        System.out.println("<==");
 
     }
 
     @Override
     public  void  run(String... args)  throws  Exception {
 
         repository.deleteAll();
 
         // save a couple of customers
         repository.save( new  Customer( "Alice" "Smith" ));
         repository.save( new  Customer( "Bob" "Smith" ));
         repository.save( new  Customer( "张" "三" ));
         repository.save( new  Customer( "李" "四" ));
         repository.save( new  Customer( "王" "五" ));
         repository.save( new  Customer( "赵" "六" ));
         repository.save( new  Customer( "周" "七" ));
         repository.save( new  Customer( "杨" "八" ));
 
         // fetch all customers
         System.out.println( "Customers found with findAll():" );
         System.out.println( "-------------------------------" );
         for  (Customer customer : repository.findAll()) {
             System.out.println(customer);
         }
         System.out.println();
 
         // fetch an individual customer
         System.out.println( "Customer found with findByFirstName('Alice'):" );
         System.out.println( "--------------------------------" );
         System.out.println(repository.findByFirstName( "Alice" ));
 
         System.out.println( "Customers found with findByLastName('Smith'):" );
         System.out.println( "--------------------------------" );
         for  (Customer customer : repository.findByLastName( "Smith" )) {
             System.out.println(customer);
         }
 
         System.out.println( "分页测试==>" );
         Page<Customer> pageData = repository.findAll( new  PageRequest( 0 4 ));
         for  (Customer c : pageData) {
             System.out.println(c);
         }
         System.out.println( "----------" );
         System.out.println(String.format( "第%d页 , 总页数:%d , 总记录数:%d , %d条/页" ,
                 pageData.getNumber() +  1 ,
                 pageData.getTotalPages(),
                 pageData.getTotalElements(),
                 pageData.getSize()
         ));
 
         //按条件动态查询
         Customer c = mongoTemplate.findOne( new  Query(Criteria.where( "firstName" ).is( "杨" )), Customer. class );
         System.out.println(c);
 
         System.out.println( "----------" );
 
         List<Customer> list = mongoTemplate.find( new  Query(Criteria.where( "firstName" ).in( "李" , "赵" )), Customer. class );
 
         for  (Customer item : list) {
             System.out.println(item);
         }
     }
 
}

github上已经开源了该项目:https://github.com/yjmyzz/spring-mongo-sample 供有需要的同学参考


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值