01 MongoDB安装与使用

Java 实现文件【夹】压缩

  • MongoDB安装
    • 下载
    • 解压缩
    • 查看启动项
    • 启动服务
  • 密码配置
    • 启动客户端
    • 创建管理员
    • 重启服务器
    • 启动客户端并登录
    • 创建普通用户
  • SpringBoot整合MongoDB
    • 引用依赖
    • yml文件配置
    • 代码中使用
  • 参考

MongoDB安装

下载

从mongodb官网下载安装包,或者使用linux wget直接下载

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.1.tgz

解压缩

cd /opt
tar zxvf mongodb-linux-x86_64-rhel70-4.4.1.tgz
mv mongodb-linux-x86_64-rhel70-4.4.1 mongodb

查看启动项

cd mongodb
bin/mongod -h

具体的启动项如下:

Options:
  --networkMessageCompressors arg (=snappy,zstd,zlib)
                                        Comma-separated list of compressors to 
                                        use for network messages

General options:
  -h [ --help ]                         显示可用的信息
  --version                             显示版本号
  -f [ --config ] arg                   指定配置文件
                                        additional options
  --configExpand arg                    Process expansion directives in config 
                                        file (none, exec, rest)
  --port arg                            指定端口号 - 默认: 27017 
  --ipv6                                Enable IPv6 support (disabled by 
                                        default)
  --listenBacklog arg (=128)            Set socket listen backlog size
  --maxConns arg (=1000000)             Max number of simultaneous connections
  --pidfilepath arg                     Full path to pidfile (if not set, no 
                                        pidfile is created)
  --timeZoneInfo arg                    Full path to time zone info directory, 
                                        e.g. /usr/share/zoneinfo
  --nounixsocket                        Disable listening on unix sockets
  --unixSocketPrefix arg                Alternative directory for UNIX domain 
                                        sockets (defaults to /tmp)
  --filePermissions arg                 Permissions to set on UNIX domain 
                                        socket file - 0700 by default
  --fork                                后台启动服务
  -v [ --verbose ] [=arg(=v)]           Be more verbose (include multiple times
                                        for more verbosity e.g. -vvvvv)
  --quiet                               Quieter output
  --logpath arg                         指定日志文件路径(不是文件夹)
  --syslog                              Log to system's syslog facility instead
                                        of file or stdout
  --syslogFacility arg                  syslog facility used for mongodb syslog
                                        message
  --logappend                           Append to logpath instead of 
                                        over-writing
  --logRotate arg                       Set the log rotation behavior 
                                        (rename|reopen)
  --timeStampFormat arg                 Desired format for timestamps in log 
                                        messages. One of iso8601-utc or 
                                        iso8601-local
  --setParameter arg                    Set a configurable parameter
  --bind_ip arg                         绑定的IP地址,使用逗号分隔 - 默认是localhost
  --bind_ip_all                         绑定所有的IP地址,0.0.0.0
  --noauth                              Run without security
  --transitionToAuth                    For rolling access control upgrade. 
                                        Attempt to authenticate over outgoing 
                                        connections and proceed regardless of 
                                        success. Accept incoming connections 
                                        with or without authentication.
  --slowms arg (=100)                   Value of slow for profile and console 
                                        log
  --slowOpSampleRate arg (=1)           Fraction of slow ops to include in the 
                                        profile and console log
  --auth                                Run with security
  --clusterIpSourceWhitelist arg        Network CIDR specification of permitted
                                        origin for `__system` access
  --profile arg                         0=off 1=slow, 2=all
  --cpu                                 Periodically show cpu and iowait 
                                        utilization
  --sysinfo                             Print some diagnostic system 
                                        information
  --noscripting                         Disable scripting engine
  --notablescan                         Do not allow table scans
  --shutdown                            Kill a running server (for init 
                                        scripts)
  --keyFile arg                         Private key for cluster authentication
  --clusterAuthMode arg                 Authentication mode used for cluster 
                                        authentication. Alternatives are 
                                        (keyFile|sendKeyFile|sendX509|x509)

Replication options:
  --oplogSize arg                       Size to use (in MB) for replication op 
                                        log. default is 5% of disk space (i.e. 
                                        large is good)

Replica set options:
  --replSet arg                         arg is <setname>[/<optionalseedhostlist
                                        >]
  --enableMajorityReadConcern [=arg(=1)] (=1)
                                        Enables majority readConcern

Sharding options:
  --configsvr                           Declare this is a config db of a 
                                        cluster; default port 27019; default 
                                        dir /data/configdb
  --shardsvr                            Declare this is a shard db of a 
                                        cluster; default port 27018

Storage options:
  --storageEngine arg                   What storage engine to use - defaults 
                                        to wiredTiger if no data files present
  --dbpath arg                          数据存放的路径 
                                        默认路径: /data/db
  --directoryperdb                      Each database will be stored in a 
                                        separate directory
  --syncdelay arg (=60)                 Seconds between disk syncs
  --journalCommitInterval arg (=100)    how often to group/batch commit (ms)
  --upgrade                             Upgrade db if needed
  --repair                              Run repair on all dbs
  --journal                             Enable journaling
  --nojournal                           Disable journaling (journaling is on by
                                        default for 64 bit)
  --oplogMinRetentionHours arg (=0)     Minimum number of hours to preserve in 
                                        the oplog. Default is 0 (turned off). 
                                        Fractions are allowed (e.g. 1.5 hours)

Free Monitoring Options:
  --enableFreeMonitoring arg            Enable Cloud Free Monitoring 
                                        (on|runtime|off)
  --freeMonitoringTag arg               Cloud Free Monitoring Tags

WiredTiger options:
  --wiredTigerCacheSizeGB arg           Maximum amount of memory to allocate 
                                        for cache; Defaults to 1/2 of physical 
                                        RAM
  --wiredTigerJournalCompressor arg (=snappy)
                                        Use a compressor for log records 
                                        [none|snappy|zlib|zstd]
  --wiredTigerDirectoryForIndexes       Put indexes and data in different 
                                        directories
  --wiredTigerCollectionBlockCompressor arg (=snappy)
                                        Block compression algorithm for 
                                        collection data [none|snappy|zlib|zstd]
  --wiredTigerIndexPrefixCompression arg (=1)
                                        Use prefix compression on row-store 
                                        leaf pages

AWS IAM Options:
  --awsIamSessionToken arg              AWS Session Token for temporary 
                                        credentials

TLS Options:
  --tlsOnNormalPorts                    Use TLS on configured ports
  --tlsMode arg                         Set the TLS operation mode 
                                        (disabled|allowTLS|preferTLS|requireTLS
                                        )
  --tlsCertificateKeyFile arg           Certificate and key file for TLS
  --tlsCertificateKeyFilePassword arg   Password to unlock key in the TLS 
                                        certificate key file
  --tlsClusterFile arg                  Key file for internal TLS 
                                        authentication
  --tlsClusterPassword arg              Internal authentication key file 
                                        password
  --tlsCAFile arg                       Certificate Authority file for TLS
  --tlsClusterCAFile arg                CA used for verifying remotes during 
                                        inbound connections
  --tlsCRLFile arg                      Certificate Revocation List file for 
                                        TLS
  --tlsDisabledProtocols arg            Comma separated list of TLS protocols 
                                        to disable [TLS1_0,TLS1_1,TLS1_2]
  --tlsAllowConnectionsWithoutCertificates 
                                        Allow client to connect without 
                                        presenting a certificate
  --tlsAllowInvalidHostnames            Allow server certificates to provide 
                                        non-matching hostnames
  --tlsAllowInvalidCertificates         Allow connections to servers with 
                                        invalid certificates
  --tlsFIPSMode                         Activate FIPS 140-2 mode at startup
  --tlsLogVersions arg                  Comma separated list of TLS protocols 
                                        to log on connect [TLS1_0,TLS1_1,TLS1_2
                                        ]

启动服务

mkdir logs #存放日志文件
mkdir -p data/db #存放数据
bin/mongod --dbpath=data/db --logpath=logs/mongo.log --bind_ip_all --port 27000 --fork

密码配置

启动客户端

bin/mongo --host 127.0.0.1 --port 27000

创建管理员

use admin
db.createUser({
  user: "admin",
  pwd:"admin",
  roles:[{role:"userAdminAnyDatabase",db:"admin"}]
})

重启服务器

重启服务器需要加上auth参数,即需要密码登录

bin/mongod --dbpath=data/db --logpath=logs/mongo.log --bind_ip_all --port 27000 --auth --fork

启动客户端并登录

bin/mongo --host 127.0.0.1 --port 27000
use admin
db.auth("admin", "admin")

创建普通用户

use dp
db.createUser({
  user: "dp",
  pwd:"dp",
  roles:[{role:"readWrite",db:"dp"}]
})
  1. 登录普通用户
use dp
db.auth("dp", "dp")

read:允许用户读取指定数据库
readWrite:允许用户读写指定数据库
dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root:只在admin数据库中可用。超级账号,超级权限

SpringBoot整合MongoDB

引用依赖

<dependency>
  <groupId>org.springframework.bootgroupId>
  <artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>

yml文件配置

spring: 
  data: 
    mongodb: 
      database: dp
      host: 127.0.0.1 #mongodb安装的主机
      port: 27000 #mongodb的端口号 
      username: dp
      password: dp

代码中使用

@Service
public class UserService {
  @Autowired
  private MongoTemplate mongoTemplate;
}

参考

  1. MongoDB设置用户名和密码

你可能感兴趣的:(MongoDB,mongodb,java,spring,boot,spring)