zoukankan      html  css  js  c++  java
  • mongodb的安装与使用(一)

    一、什么是MongoDB ?

    MongoDB一种由C++语言编写的,是一个基于分布式文件存储的非关系型数据库(NoSql),是一种强大、灵活、可扩展的数据存储方式,因为MongoDB是文档模型,数据结构由键值(key=>value)对组成,

    似于 JSON 对象,字段值可以包含其他文档,数组及文档数组。自由灵活很高。

    同时对于大数据量、高并发、弱事务的互联网应用,与高负载的情况下,添加更多的节点,可以保证服务器性能。

    MongoDB内置的水平扩展机制提供了从百万到十亿级别的数据量处理能力,还对MapReduce式聚合的支持,以及对地理空间索引的支持。

    MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。

    二、MongoDB 优缺点

    优点

    • 文档结构的存储方式,能够更便捷的获取数据
    • 内置GridFS,支持大容量的存储
    • 海量数据下,性能优越
    • 动态查询
    • 全索引支持,扩展到内部对象和内嵌数组
    • 查询记录分析
    • 快速,就地更新
    • 高效存储二进制大对象 (比如照片和视频)
    • 复制(复制集)和支持自动故障恢复
    • 内置 Auto- Sharding 自动分片支持云级扩展性,分片简单
    • MapReduce 支持复杂聚合

    缺点

    • 不支持事务操作
    • MongoDB 占用空间过大 (不过这个确定对于目前快速下跌的硬盘价格来说,也不算什么缺点了)
    • MongoDB没有如MySQL那样成熟的维护工具
    • 无法进行关联表查询,不适用于关系多的数据
    • 复杂聚合操作通过mapreduce创建,速度慢
    • 模式自由,自由灵活的文件存储格式带来的数据错
    • MongoDB 在你删除记录后不会在文件系统回收空间。除非你删掉数据库。但是空间没有被浪费

    三、优缺点详细解释

    与关系型数据库相比,MongoDB的优点:

    1.内置GridFS,支持大容量的存储:

      GridFS是一个出色的分布式文件系统,可以支持海量的数据存储。 内置了GridFS了MongoDB,能够满足对大数据集的快速范围查询。

    2.内置 Auto- Sharding 自动分片支持云级扩展性,分片简单

      提供基于Range的Auto Sharding机制:

      一个collection可按照记录的范围,分成若干个段,切分到不同的Shard上。

      Shards可以和复制结合,配合Replica sets能够实现Sharding+fail-over,不同的Shard之间可以负载均衡。
      查询是对客户端是透明的。客户端执行查询,统计,MapReduce等操作,这些会被MongoDB自动路由到后端的数据节点。
      这让我们关注于自己的业务,适当的 时候可以无痛的升级。MongoDB的Sharding设计能力最大可支持约20 petabytes,足以支撑一般应用。
      这可以保证MongoDB运行在便宜的PC服务器集群上。PC集群扩充起来非常方便并且成本很低,避免了“sharding”操作的复杂性和成本。

    3.海量数据下,性能优越:

      在使用场合下,千万级别的文档对象,近10G的数据,对有索引的ID的查询不会比mysql慢,mysql实际无法胜任大数据量下任意字段的查询,所以mongo对非索引字段的查询,则是更胜一筹,

      而mongodb的查询性与写入性能同样很令人满意,同样写入百万级别的数据,基本10分钟以下可以解决且mongodb都远算不上是CPU杀手。

    4.全索引支持,扩展到内部对象和内嵌数组

      索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。

      这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可以要花费几十秒甚至几分钟,这对网站的性能是非常致命的。

      索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构。

    5.MapReduce 支持复杂聚合

      MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。

    与关系型数据库相比,MongoDB的缺点:

    mongodb不支持事务操作:

      所以事务要求严格的系统(如果银行系统)肯定不能用它。

    mongodb不支持事务操作:

      所以事务要求严格的系统(如果银行系统)肯定不能用它。

    mongodb占用空间过大:

    关于其原因,在官方的FAQ中,提到有如下几个方面:

    1、空间的预分配:为避免形成过多的硬盘碎片,mongodb每次空间不足时都会申请生成一大块的硬盘空间,而且申请的量从64M、128M、256M那 样的指数递增,直到2G为单个文件的最大体积。随着数据量的增加,你可以在其数据目录里看到这些整块生成容量不断递增的文件。

    2、字段名所占用的空间:为了保持每个记录内的结构信息用于查询,mongodb需要把每个字段的key-value都以BSON的形式存储,如果 value域相对于key域并不大,比如存放数值型的数据,则数据的overhead是最大的。一种减少空间占用的方法是把字段名尽量取短一些,这样占用 空间就小了,但这就要求在易读性与空间占用上作为权衡了。

    3、删除记录不释放空间:这很容易理解,为避免记录删除后的数据的大规模挪动,原记录空间不删除,只标记“已删除”即可,以后还可以重复利用。

    4、可以定期运行db.repairDatabase()来整理记录,但这个过程会比较缓慢

    MongoDB没有如MySQL那样成熟的维护工具,这对于开发和IT运营都是个值得注意的地方。

    4.安装前言

    monogb还没有win10版本

    https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-windows/

    5.安装mongo

    1.安装和配置

      第一步:解压到一个盘上,例如我的解压的目录D:oomongodb,如图所示:

    第二步:配置存放日志和数据的目录,不然mongoDB无法启动,如图所示:

     

     通过帮助命令,找到了(1)--logpath arg: arg是设置存放日志的路径(2)--dbpath arg:arg是存放数据文件的路径

    C:UsersWQBin>mongod --help
    Options:
      --networkMessageCompressors arg (=snappy,zstd,zlib)
                                            Comma-separated list of compressors to
                                            use for network messages
    
    General options:
      -h [ --help ]                         Show this usage information
      --version                             Show version information
      -f [ --config ] arg                   Configuration file specifying
                                            additional options
      --configExpand arg                    Process expansion directives in config
                                            file (none, exec, rest)
      --ipv6                                Enable IPv6 support (disabled by
                                            default)
      --listenBacklog arg (=2147483647)     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
      -v [ --verbose ] [=arg(=v)]           Be more verbose (include multiple times
                                            for more verbosity e.g. -vvvvv)
      --quiet                               Quieter output
      --port arg                            Specify port number - 27017 by default
      --logpath arg                         Log file to send write to instead of
                                            stdout - has to be a file, not
                                            directory
      --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 ctime, iso8601-utc or
                                            iso8601-local
      --setParameter arg                    Set a configurable parameter
      --bind_ip arg                         Comma separated list of ip addresses to
                                            listen on - localhost by default
      --bind_ip_all                         Bind to all ip addresses
      --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
      --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                          Directory for datafiles - defaults to
                                            datadb which is C:datadb based on
                                            the current working drive
      --directoryperdb                      Each database will be stored in a
                                            separate directory
      --syncdelay arg (=60)                 Seconds between disk syncs (0=never,
                                            but not recommended)
      --journalCommitInterval arg (=100)    how often to group/batch commit (ms)
      --noIndexBuildRetry                   Do not retry any index builds that were
                                            interrupted by shutdown
      --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)
    
    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
      --tlsCertificateSelector arg          TLS Certificate in system store
      --tlsClusterCertificateSelector arg   SSL/TLS Certificate in system store for
                                            internal TLS authentication
      --tlsLogVersions arg                  Comma separated list of TLS protocols
                                            to log on connect [TLS1_0,TLS1_1,TLS1_2
                                            ]
    
    Windows Service Control Manager options:
      --install                             Install Windows service
      --remove                              Remove Windows service
      --reinstall                           Reinstall Windows service (equivalent
                                            to --remove followed by --install)
      --serviceName arg                     Windows service name
      --serviceDisplayName arg              Windows service display name
      --serviceDescription arg              Windows service description
      --serviceUser arg                     Account for service execution
      --servicePassword arg                 Password used to authenticate
                                            serviceUser
    
    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
      --wiredTigerMaxCacheOverflowFileSizeGB arg (=0)
                                            Maximum amount of disk space to use for
                                            cache overflow; Defaults to 0
                                            (unbounded)
      --wiredTigerCollectionBlockCompressor arg (=snappy)
                                            Block compression algorithm for
                                            collection data [none|snappy|zlib|zstd]
      --wiredTigerIndexPrefixCompression arg (=1)
                                            Use prefix compression on row-store
                                            leaf pages
    mongod --help

    先在目录下建立相关的存储日志的文件和存储数据的文件夹

    mongod  --logpath  D:oomongodblogslog
    mongod  --dbpath  D:oomongodbdata

     这样就建立一个monog的服务端:

     

    也可以直接把配置写入文件中,直接mongod  --config d:oomongodbmongodb.config打开相应的服务端

     通过mongo命令直接打开客户端:

     

    6.添加MongoDB到Windows Service

    第一步:安装MongoDB自动服务

         我们当我们把运行MongoDB服务器的dos命令界面关掉,MongoDB的客户端也随之停止。

        如果把mongo 的服务端添加到Windows Service,然后在命令行上启动服务和关闭服务,这样方便我们操作和管理服务,用到的命令是--install设定安装MongoDB为服务器到Windows Service。

    第二步:启动/关闭MongoDB服务

       netstart mongodb 启动MongoDB服务

      net stop mongodb 启动MongoDB服

  • 相关阅读:
    Windows搭建SkyWalking8.3环境进行JAVA应用性能监控及入门示例(使用Mysql持久化)
    使用JMeter进行压力测试
    IDEA2020.1使用LeetCode插件运行并调试本地样例
    centos7使用Minikube“快速搭建“出Kubernetes本地实验环境(踩坑集锦及解决方案)
    事务的隔离级别与所带来的问题
    深入理解HashMap第一篇
    LoadRunner 与浏览器兼容性
    互联网产品接入支付功能如何测试?
    基于AMF协议的Flex应用程序的性能测试
    centos+mono+nginx+jexus 搭建linux下c#运行环境测试
  • 原文地址:https://www.cnblogs.com/wqbin/p/11792702.html
Copyright © 2011-2022 走看看