mongodb 速成笔记
来源:互联网 发布:淘宝有名片设计吗 编辑:程序博客网 时间:2024/06/05 17:07
以下环境为mac osx + jdk 1.8 + mongodb v3.2.3
一、安装
brew安装方式是mac下最简单的方式
brew update
brew
install
mongodb
其它OS上的安装请参考:https://docs.mongodb.org/manual/installation/
二、启动
2.1 最基本的启动
mongod
不加任何参数时,db默认保存在/data/db目录(如果该目录不存在,启动会报错),监听的端口是27017,且不启动安全认证机制(即:谁都可以连接,只要连接上来的用户都是管理员)
2.2 指定dbpath
mongod --dbpath ~
/data/db/mongo
指定dbpath后,数据文件将保存在指定的目录下(注意:该目录必须有读写权限)
2.3 指定端口
mongod --dbpath ~
/data/db/mongo
--port 12345
2.4 启用安全认证
mongod --dbpath ~
/data/db/mongo
--port 12345 --auth
这个下面还会仔细讲解,这里只要记得有--auth这个选项即可。
2.5 其它一些选项
mongod --help
如果想详细了解所有启动选项,可以加--help查看所有可选参数。
启动成功后,可以用 mongo 命令来连接
➜ ~ 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 创建数据库
use mydb
跟mysql差不多,use 后加数据库名称即可,如果数据库不存在,会自动创建。假设以下的所有安全相关的操作,都是在mydb这个库下。
3.1 创建用户
切换到相对的db后,使用下面的命令创建用户
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 授权
db.auth({
user:
"admin"
,
pwd
:
"123456"
})
3.3 用--auth 重启mongod
mongod --auth
3.4 客户端连接时,指定安全信息
mongo localhost:27017
/mydb
-u admin -p 123456 --authenticationDatabase mydb
大家参考上面的命令修改相关参数(比如:端口号之类的),连接上去后,可以尝试
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文件
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'
其实关键的只有一行:
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
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使用示例
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 供有需要的同学参考
- mongodb 速成笔记
- mongodb 速成笔记
- SEO半小时速成笔记
- 速成笔记:Javascript
- 速成笔记:Servlet
- git 速成笔记
- 8天速成mongoDB(一)
- 速成笔记:Cascade Style Sheet
- 速成笔记:Java DataBase Connectivity
- 速成笔记:Procedural Language SQL
- 速成笔记:Hypertext Transfer Protocol
- 速成笔记:Java Server Pages
- IOS开发-AFNetWorking速成笔记
- IDA一日速成整理笔记
- AngularJS 学习笔记-第一章:速成
- python一周速成学习笔记
- 速成
- jsp基础速成精华讲解(笔记)
- 百度之星1006度度熊的01世界
- 多态的动态绑定
- c语言初步经典题9--分离浮点数的整数和小数
- 如何将PCB边角从直角改为弧形 1
- 平衡树(摘自各种材料)(2577 Vojnici)
- mongodb 速成笔记
- Java 邮件发送功能
- docker设置centos容器支持
- bzoj2301 莫比乌斯反演
- RMI(Remote method invoke)详解
- angularjs中基本功能用法
- Python遍历文件夹 处理json文件
- 初窥Linux 之 我最常用的20条命令
- HDU 4622 Reincarnation(后缀自动机)