mongodb 速成笔记

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 以下环境为mac osx + jdk 1.8 + mongodb v3.2.3 一、安装 brew安装方式是mac下最简单的方式 brew update brew install mongodb 其它OS上的安装请参考:https://docs.

以下环境为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接口

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 {

    @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数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
5月前
|
运维 NoSQL MongoDB
[慕课笔记]mongodb入门篇
[慕课笔记]mongodb入门篇
41 1
|
5月前
|
前端开发 JavaScript NoSQL
[慕课笔记] node+mongodb建站攻略
[慕课笔记] node+mongodb建站攻略
25 0
|
NoSQL JavaScript MongoDB
MongoDB随手笔记(二)
MongoDB随手笔记(二)
MongoDB随手笔记(二)
|
SQL 存储 JSON
MongoDB随手笔记(一)
MongoDB随手笔记(一)
MongoDB随手笔记(一)
|
存储 JSON NoSQL
mongodb笔记
mongodb笔记
336 0
|
存储 NoSQL MongoDB
MongoDB基础知识笔记
MongoDB基础知识笔记
150 0
|
存储 JSON NoSQL
MongoDB 入门笔记
MongoDB 简介 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。在高负载的情况下,添加更多的节点,可以保证服务器性能。MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。 MongoDB 的安装 我用的是 linux,因此可以用以下命令进行安装:
184 0
|
NoSQL Linux
MongoDB 生产环境笔记
MongoDB 生产环境笔记目录 MongoDB 生产环境笔记一、vm.zone_reclaim_mode 参数二、添加 swap 分区三、设置 swappiness 参数四、内核和文件系统版本五、禁用 Transparent Huge Pages (THP)六、ulimit 设置七、tcp_keepalive_time八、同步时间MongoDB 生产环境笔记在生产环境中,我们配置MongoDB需要注意点有很多,而不是一安装就可以使用。
2100 0
|
安全 NoSQL 数据库
公网访问阿里云数据库MongoDB——填坑笔记
业务情景 两台服务器,一台阿里云ECS云服务器(专用网络),另一台是阿里云数据库MongoDB,处于安全考虑MongoDB是不运行外网连接的,那接下来就看怎么实现公网访问。 看到上面红色的网络类型描述,有些人可能已经看出问题所在了,小小的提示:问题出现在开放端口上! 专用网络和经典网络的大致区...
3130 0
|
NoSQL 数据库
MongoDB 安装笔记
一、MongoDB的安装 1.在MongoDB的官网下载对应的安装文件() 2.解压安装文件 #解压tgz文件 tar -zxvf mongodb-linux-x86_64-ubuntu1604-3.6.2.tgz #将解压好的文件放到指定目录下 mv mongodb-linux-x86_64-ubuntu1604-3.6.2/ /usr/local/mongodb #配置环境变量 export PATH=/bin:$PATH # 为你 MongoDB 的安装路径。
1006 0