mongodb 速成笔记
以下环境为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.8buildscript {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 {@Idprivate String id;private String firstName;private String lastName;public Customer() {}public Customer(String firstName, String lastName) {this.firstName = firstName;this.lastName = lastName;}@Overridepublic 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接口
package com.cnblogs.yjmyzz.mongo.repository;import com.cnblogs.yjmyzz.mongo.model.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;import java.util.List;public interface CustomerRepository extends MongoRepository<Customer, String> {public Customer findByFirstName(String firstName);public List<Customer> findByLastName(String lastName);}
这里有一些默认的约定要理解,比如上面的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 {@Autowiredprivate CustomerRepository repository;@AutowiredMongoTemplate 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("<==");}@Overridepublic void run(String... args) throws Exception {repository.deleteAll();// save a couple of customersrepository.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 customersSystem.out.println("Customers found with findAll():");System.out.println("-------------------------------");for (Customer customer : repository.findAll()) {System.out.println(customer);}System.out.println();// fetch an individual customerSystem.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学习笔记(入门)
MongoDB学习笔记(入门) 一.文档的注意事项: 1. 键值对是有序的,如:{ "name" : "stephen", "genda" ...
- MongoDB学习笔记【2】-- 试用
大部分内容根据MongoDB官方手册整理:http://docs.mongodb.org/manual/contents/ 查看数据库 [root@slayer ~]# mongo MongoDB s ...
- MongoDB学习笔记(四)使用Java进行实时监控与数据收集(空间使用量、连接数)
目录: MongoDB学习笔记(一)环境搭建与常用操作 MongoDB学习笔记(二)使用Java操作MongoDB MongoDB学习笔记(三)使用Spring Data操作MongoDB Mongo ...
- MongoDB学习笔记(一) MongoDB介绍及安装
系列目录 MongoDB学习笔记(一) MongoDB介绍及安装 MongoDB学习笔记(二) 通过samus驱动实现基本数据操作 MongoDB学习笔记(三) 在MVC模式下通过Jq ...
- PHP操作MongoDB学习笔记
PHP操作MongoDB技術總結 <?php /** * PHP操作MongoDB学习笔记 */ //************************* //** 连接MongoDB数据库 ...
- MongoDB学习笔记(四)--索引 性能优化
索引 基础索引 ...
- MongoDB学习笔记一:MongoDB的下载和安装
MongoDB学习笔记一:MongoDB的下载和安装 趁着这几天比較空暇,准备学习一下MongoDB数据库.今天就简单的学习了一些MongoDB的下载和安装.并创建了存储MongoDB的数据仓库. 将 ...
- MongoDB 学习笔记八 复制、分片、备份与恢复、监控
MongoDB 学习笔记八 复制.分片.备份与恢复.监控 MongoDB复制(副本集) 什么是复制? MongoDB 复制原理 MongoDB 副本集设置 副本集添加成员 MongoDB 分片 分片 ...
- MongoDB学习笔记~对集合属性的操作
$unset清除元素 请注意在单个数组元素上使用$unset的结果可能与你设想的不一样.其结果只是将元素的值设置为null,而非删除整个元素.要想彻底删除某个数组元素,可以用$pull 和$pop操作 ...
最新文章
- linux下vi命令修改文件及保存的使用方法
- hibernate xxx is not mapped 错误原因及解决方法
- 【工具】公网临时大文件传输工具,文件发送,高速文件传输方法
- 转:自定义谷歌地图配色方案
- python lua 性能比较 内存_Lua 的速度为什么比 Python 快?
- java map转string_【库学科技】32道常见的Java基础面试题
- Java案例:Karel学习Java
- 在某个时间段查找某连续出现问题
- 计算机代数与数论pdf,计算机代数和数论(maple).pdf
- IIC,SPI,I2S
- 用计算机求回归,鲜为人知的用途,回归分析用计算器就能做!
- 【吐血整理】超全golang面试题合集+golang学习指南+golang知识图谱+成长路线 一份涵盖大部分golang程序员所需要掌握的核心知识。
- 罗翔老师转谈记录,不同认知出发//心之所向,素履以往,生如逆旅,一苇以航。
- 台式机插上耳机,声音仍然外放问题解决
- Canvas 画椭圆的方法
- 李航 统计学习方法 课后习题答案 第二版
- ComponentOne C1ReportDesigner 设计报表
- sharemouse怎么设置?
- git merge之--no-ff 的作用
- 计算机毕业设计(附源码)python医院管理系统
热门文章
- nfs挂载出错:mount.nfs: access denied by server while mounting
- Python3常用字符串操作
- 解决了asp.net 关于服务器版本不正确的问题
- I.MX6 Android 设备节点权限
- Spark学习之Spark Streaming(9)
- 正确设置Android Support Library
- 怎样做才是一个独立自主的人?
- CStatic控件的基本使用
- braft的LogEntry日志记录存储LogStorage
- 【免费毕设】ASP.NET电子购物商城系统(源代码+lunwen)