关于mongodb:MongoDB的安装与连接

3次阅读

共计 13978 个字符,预计需要花费 35 分钟才能阅读完成。

MongoDB 简介

MongoDB 是一种以文档的模式存储的 NoSQL 数据库。MongoDB 分付费版和收费版本,云服务版本 Atlas 和企业高级版本是须要付费的。MongoDB 社区版本是开源的,开源代码仓库地址是:
https://github.com/mongodb/mongo

MongoDB 次要分为以下三个局部:

  • mongod – 数据库服务
  • mongos – 分片路由
  • mongo – 命令行客户端

MongoDB 的装置

Homebrew 装置

如果你用的是 MacOS 零碎,一种可用的形式是应用 Homebrew 软件管理系统进行装置。brew 命令的应用及参数阐明如下:

$ brew --help
Example usage:
  brew search [TEXT|/REGEX/]
  brew info [FORMULA...]
  brew install FORMULA...
  brew update
  brew upgrade [FORMULA...]
  brew uninstall FORMULA...
  brew list [FORMULA...]

Troubleshooting:
  brew config
  brew doctor
  brew install --verbose --debug FORMULA

Contributing:
  brew create [URL [--no-fetch]]
  brew edit [FORMULA...]

Further help:
  brew commands
  brew help [COMMAND]
  man brew
  https://docs.brew.sh

装置前最好应用如下命令先更新一下软件包仓库。

brew update

如果想要装置的是包管理器中的默认版本,应用如下的命令装置即可。

brew install mongodb

如果你不晓得有哪些版本的 MongoDB 可用,能够应用安装包搜寻命令行搜寻一下 Homebrew 反对的版本,并抉择相应的版本进行装置。

brew search mongodb

如果你不分明之前你有没有装置过,或者装置的是哪个版本,能够应用如下命令进行查问。

brew info mongodb

源代码编译装置

如果用的不是惯例的 Linux、MacOS、Windows 等操作系统。你可下载 MongoDB 的源代码进行构建后装置与运行。
具体的构建过程能够参考如下链接:
https://github.com/mongodb/mongo/blob/master/docs/building.md

离线包装置

如果你用的是惯例的操作系统,个别状况下,只须要间接下载编译好的包装置即可。安装包的下载地址为:

  • 企业版
  • 社区版

依据你的操作系统及 CPU 型号,抉择下载不同版本的安装包,进行装置即可。

  • 如果你的操作系统是 Redhat,下载.rpm 文件后,应用 yum 命令进行装置。
  • 如果你的操作系统是 Ubuntu,下载.deb 文件后,应用 apt-get 命令进行装置。
  • 如果你的操作系统是 Windows,下载.msi 文件后,间接点击后进行装置。
  • 如果你应用的是 MacOS,只能下载.tgz 的压缩包,解压后运行 mongod 服务即可。

不论你是哪种零碎,其实都提供了.tgz 或.zip 格局的压缩包,如果找不到相应操作系统的安装包,你能够抉择压缩包的形式进行下载安装。

Docker 形式装置

我举荐的装置形式是应用 Docker 镜像的形式装置与应用 MongoDB。因为 Docker 的形式运行与治理服务比拟不便,运行环境与本机环境互相隔离,能够防止相互之间的诸多烦扰。

在应用 Docker 装置 monbodb 之前,当然你须要先筹备好 docker 的运行环境。如果你还没有装置 docker,请参考官网进行装置,这里不作具体介绍。

如果你是集体钻研应用,倡议你间接下载安装 Docker Desktop 版本。

docke 运行环境筹备好当前,你能够应用如下的命令查问可抉择的 MongoDB 镜像。

$ docker search mongodb
NAME                                    DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mongo                                   MongoDB document databases provide high avai…   8848      [OK]       
mongo-express                           Web-based MongoDB admin interface, written w…   1180      [OK]       
bitnami/mongodb                         Bitnami MongoDB Docker Image                    177                  [OK]
percona/percona-server-mongodb          Percona Server for MongoDB docker images        36                   
rapidfort/mongodb                       RapidFort optimized, hardened image for Mong…   13                   
circleci/mongo                          CircleCI images for MongoDB                     11                   [OK]
bitnami/mongodb-sharded                                                                 7                    
bitnami/mongodb-exporter                                                                6                    
edgexfoundry/docker-edgex-mongo         ARCHIVED! MongoDB container for older versio…   5                    
rancher/mongodb-conf                                                                    2                    
percona/mongodb_exporter                A Prometheus exporter for MongoDB including …   2                    
ibmcom/mongodb-ppc64le                                                                  1                    
edgexfoundry/docker-edgex-mongo-seed    ARCHIVED!Initializer for MongoDB for early E…   1                    
edgexfoundry/docker-edgex-mongo-arm64   ARCHIVED! ARM64 MongoDB container for older …   1                    
ibmcom/mongodb                                                                          1                    
jhipster/jhipster-sample-app-mongodb    This is a sample application created with JH…   1                    [OK]
kope/mongodb                                                                            0                    
ibmcom/mongodb-exporter-ppc64le                                                         0                    
ibmcom/mongodb-s390x                                                                    0                    
ibmcom/mongodb-amd64                                                                    0                    
rapidfort/mongodb-perfomance-test                                                       0                    
radarbase/kafka-connect-mongodb-sink    Kafka MongoDB sink connector                    0                    
rancher/mongodb-config                                                                  0                    
radarbase/radar-hotstorage              Upon the first start, this dockerised MongoD…   0                    
drud/mongodb                            Mongodb                                         0                    [OK]

我个别抉择是 STARS 比拟高的镜像进行装置。你须要先通过 docker pull 命令将 Docker 镜像下载的本地。

$ docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
d7bfe07ed847: Pull complete 
97ef66a8492a: Pull complete 
20cec14c8f9e: Pull complete 
38c3018eb09a: Pull complete 
ccc9e1c2556b: Pull complete 
593c62d03532: Pull complete 
1a103a446c3f: Pull complete 
be887b845d3f: Pull complete 
e5543880b183: Pull complete 
Digest: sha256:37e84d3dd30cdfb5472ec42b8a6b4dc6ca7cacd91ebcfa0410a54528bbc5fa6d
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latest

你能够应用 docker images 命令查看本地曾经下载好的所有 Docker 镜像。

 $ docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
mongo        latest    c8b57c4bf7e3   4 days ago     701MB
nginx        latest    fa5269854a5e   8 weeks ago    142MB
ubuntu       latest    ff0fea8310f3   3 months ago   72.8MB

如果你应用的是 Docker Desktop,在 Dashboard 的Images 栏也能够看到曾经下载的所有镜像。

而后你就能够应用 docker 命令启动 MongoDB 服务了。

$ docker run --name mongodb -d -p 27017:27017 mongo
4a4df84c4bb959609a5754e0b8a94bcd7c272e42ad819af2dee12b72511e2dc9

上述命令中:

  • –name 参数指定了运行容器的名字
  • -d 参数示意在后盾运行
  • -p 27017:27017 指定了本机端口及 monbod 服务的端口
  • 最初的 mongo 就是镜像的名字

如果你想要进入到窗器命令行进一步操作,能够应用如下的命令:

docker exec -it 4a4df84c4bb959609a5754e0b8a94bcd7c272e42ad819af2dee12b72511e2dc9 /bin/sh

docker exec -it mongodb /bin/sh

如果想要进行运行 MongoDB,只需执行如下命令即可。

docker stop mongodb

如果你不晓得以后有哪些容器在运行,能够应用 docker ps 命令。

$ docker ps 
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                      NAMES
4a4df84c4bb9   mongo     "docker-entrypoint.s…"   25 minutes ago   Up 25 minutes   0.0.0.0:27017->27017/tcp   mongodb

如果想要查看已进行运行的窗口,须要增 -a 参数。

$ docker ps -a
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS                      PORTS                  NAMES
4a4df84c4bb9   mongo           "docker-entrypoint.s…"   27 minutes ago   Exited (0) 46 seconds ago                          mongodb
6509ea364e65   nginx           "/docker-entrypoint.…"   6 weeks ago      Exited (255) 5 weeks ago    0.0.0.0:8888->80/tcp   nginx
81d2af2b4084   ubuntu:latest   "bash"                   2 months ago     Exited (0) 2 weeks ago                             ubuntu

如果想要再次启动已进行的 mongodb Docker 容器,只需运行 dokcer start 命令即可。

 docker start mongodb

连贯数据库

连贯串

在介绍连贯工具以前,先给大家介绍一下 MongoDB 的数据库连贯串的格局,个别如下:

mongodb:// 用户名: 明码 @主机名: 端口 / 数据库名? 连贯参数

例如,

mongodb://localhost:27017/test?readPreference=primary&ssl=false

连贯工具

连贯 MongoDB 的工具比拟多,上面列几种我晓得的。

MongoDB VS Code 插件

如果你应用的是 VS Code IDE 工具,你能够装置 IDE 的插件后进行连贯。

命令行工具 MongoDB Shell

MongoDB 的命令行工具也有好几种,你能够到官网下载本人喜爱的工具。上面我就以 mongosh 为例介绍如何应用。


和 MonboDB 的装置办法一样,也能够应用 brew intall mongosh 命令进行装置。如果你想要应用最新版本的mongosh,你能够间接下载压缩包后解压应用,

你能够应用 wget 命令通过命令行下载,或者应用浏览器的下载管理器进行下载。

download 20220618 $ wget https://downloads.mongodb.com/compass/mongosh-1.5.0-darwin-x64.zip
--2022-06-18 17:40:44--  https://downloads.mongodb.com/compass/mongosh-1.5.0-darwin-x64.zip
Resolving downloads.mongodb.com... 2600:9000:2200:8200:a:7588:fa00:93a1, 2600:9000:2200:d400:a:7588:fa00:93a1, 2600:9000:2200:1000:a:7588:fa00:93a1, ...
Connecting to downloads.mongodb.com|2600:9000:2200:8200:a:7588:fa00:93a1|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 53504066 (51M) [application/octet-stream]
Saving to: 'mongosh-1.5.0-darwin-x64.zip'

mongosh-1.5.0-darwin-x64.zip              100%[===================================================================================>]  51.03M  14.2MB/s    in 4.9s    

2022-06-18 17:40:50 (10.4 MB/s) - 'mongosh-1.5.0-darwin-x64.zip' saved [53504066/53504066]

download 20220618 $ ls
mongosh-1.5.0-darwin-x64.zip

zip 的压缩包,你能够应用 unzip 进行解压。

$ unzip mongosh-1.5.0-darwin-x64.zip 
Archive:  mongosh-1.5.0-darwin-x64.zip
   creating: mongosh-1.5.0-darwin-x64/
  inflating: mongosh-1.5.0-darwin-x64/THIRD_PARTY_NOTICES  
  inflating: mongosh-1.5.0-darwin-x64/._THIRD_PARTY_NOTICES  
   creating: mongosh-1.5.0-darwin-x64/bin/
  inflating: mongosh-1.5.0-darwin-x64/bin/mongosh_crypt_v1.dylib  
  inflating: mongosh-1.5.0-darwin-x64/bin/mongosh  
  inflating: mongosh-1.5.0-darwin-x64/LICENSE-crypt-library  
  inflating: mongosh-1.5.0-darwin-x64/._LICENSE-crypt-library  
  inflating: mongosh-1.5.0-darwin-x64/LICENSE-mongosh  
  inflating: mongosh-1.5.0-darwin-x64/._LICENSE-mongosh  
  inflating: mongosh-1.5.0-darwin-x64/README  
  inflating: mongosh-1.5.0-darwin-x64/._README  
  inflating: mongosh-1.5.0-darwin-x64/mongosh.1.gz  
  inflating: mongosh-1.5.0-darwin-x64/._mongosh.1.gz 

进入到解压目录,应用 ls 命令查看目录下的内容。

$ cd mongosh-1.5.0-darwin-x64 
mongosh-1.5.0-darwin-x64 20220618 $ ls
LICENSE-crypt-library    LICENSE-mongosh        README            THIRD_PARTY_NOTICES    bin            mongosh.1.gz
mongosh-1.5.0-darwin-x64 20220618 $ ls bin
mongosh            mongosh_crypt_v1.dylib

在 bin 目录下,能够看到 mongosh 命令。

装置好当前,能够应用 help 命令查看帮忙。或参考官网文档

$ bin/mongosh --help

  $ mongosh [options] [db address] [file names (ending in .js or .mongodb)]

  Options:

    -h, --help                                 Show this usage information
    -f, --file [arg]                           Load the specified mongosh script
        --host [arg]                           Server to connect to
        --port [arg]                           Port to connect to
        --version                              Show version information
        --verbose                              Increase the verbosity of the output of the shell
        --quiet                                Silence output from the shell during the connection process
        --shell                                Run the shell after executing files
        --nodb                                 Don't connect to mongod on startup - no'db address' [arg] expected
        --norc                                 Will not run the '.mongoshrc.js' file on start up
        --eval [arg]                           Evaluate javascript
        --retryWrites                          Automatically retry write operations upon transient network errors (Default: true)

  Authentication Options:

    -u, --username [arg]                       Username for authentication
    -p, --password [arg]                       Password for authentication
        --authenticationDatabase [arg]         User source (defaults to dbname)
        --authenticationMechanism [arg]        Authentication mechanism
        --awsIamSessionToken [arg]             AWS IAM Temporary Session Token ID
        --gssapiServiceName [arg]              Service name to use when authenticating using GSSAPI/Kerberos
        --sspiHostnameCanonicalization [arg]   Specify the SSPI hostname canonicalization (none or forward, available on Windows)
        --sspiRealmOverride [arg]              Specify the SSPI server realm (available on Windows)

  TLS Options:

        --tls                                  Use TLS for all connections
        --tlsCertificateKeyFile [arg]          PEM certificate/key file for TLS
        --tlsCertificateKeyFilePassword [arg]  Password for key in PEM file for TLS
        --tlsCAFile [arg]                      Certificate Authority file for TLS
        --tlsAllowInvalidHostnames             Allow connections to servers with non-matching hostnames
        --tlsAllowInvalidCertificates          Allow connections to servers with invalid certificates
        --tlsCertificateSelector [arg]         TLS Certificate in system store (Windows and macOS only)
        --tlsCRLFile [arg]                     Specifies the .pem file that contains the Certificate Revocation List
        --tlsDisabledProtocols [arg]           Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2]
        --tlsUseSystemCA                       Load the operating system trusted certificate list

  API version options:

        --apiVersion [arg]                     Specifies the API version to connect with
        --apiStrict                            Use strict API version mode
        --apiDeprecationErrors                 Fail deprecated commands for the specified API version

  FLE Options:

        --awsAccessKeyId [arg]                 AWS Access Key for FLE Amazon KMS
        --awsSecretAccessKey [arg]             AWS Secret Key for FLE Amazon KMS
        --awsSessionToken [arg]                Optional AWS Session Token ID
        --keyVaultNamespace [arg]              database.collection to store encrypted FLE parameters
        --kmsURL [arg]                         Test parameter to override the URL of the KMS endpoint

  DB Address Examples:

        foo                                    Foo database on local machine
        192.168.0.5/foo                        Foo database on 192.168.0.5 machine
        192.168.0.5:9999/foo                   Foo database on 192.168.0.5 machine on port 9999
        mongodb://192.168.0.5:9999/foo         Connection string URI can also be used

  File Names:

        A list of files to run. Files must end in .js and will exit after unless --shell is specified.

  Examples:

        Start mongosh using 'ships' database on specified connection string:
        $ mongosh mongodb://192.168.0.5:9999/ships

  For more information on usage: https://docs.mongodb.com/mongodb-shell.

应用 mongosh + 数据库连贯串 的命令格局就能够连贯 MongoDB 数据库。

 $ bin/mongosh mongodb://localhost:27017/test?readPreference=primary&ssl=false
[1] 95538
zsh: no matches found: mongodb://localhost:27017/test?readPreference=primary                                                                                          
[1]  + exit 1     bin/mongosh mongodb://localhost:27017/test?readPreference=primary
mongosh-1.5.0-darwin-x64 20220618 $ bin/mongosh mongodb://localhost:27017/?readPreference=primary&ssl=false 
[1] 96068
zsh: no matches found: mongodb://localhost:27017/?readPreference=primary                                                                                              
[1]  + exit 1     bin/mongosh mongodb://localhost:27017/?readPreference=primary
mongosh-1.5.0-darwin-x64 20220618 $ bin/mongosh 'mongodb://localhost:27017/test?readPreference=primary&ssl=false'
Current Mongosh Log ID:    62ad9f8dcf4bc59ca9c419d4
Connecting to:        mongodb://localhost:27017/test?readPreference=primary&ssl=false&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.0
Using MongoDB:        5.0.9
Using Mongosh:        1.5.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2022-06-18T09:17:35.706+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2022-06-18T09:17:36.761+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

------
   Enable MongoDB's free cloud-based monitoring service, which will then receive and display
   metrics about your deployment (disk utilization, CPU, operation statistics, etc).
   
   The monitoring data will be available on a MongoDB website with a unique URL accessible to you
   and anyone you share the URL with. MongoDB may use this information to make product
   improvements and to suggest MongoDB products and deployment options to you.
   
   To enable free monitoring, run the following command: db.enableFreeMonitoring()
   To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
------

Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
  You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.
test> 

而后你能够应用 MongoDB 的命令操作 MongoDB 数据库了。

test> db.test.insertOne({name:'zhangshan'})
{
  acknowledged: true,
  insertedId: ObjectId("62ada01d12bb4d27b24d3a6c")
}
test> db.test.findOne()
{_id: ObjectId("62ada01d12bb4d27b24d3a6c"), name: 'zhangshan' }
test> 

MongoDB Compass

首先须要去官网下载安装包。

如果你应用的 MacOS,点击执行下载的安装包后,会弹出如下的界面。你须要将 MongoDB Compass 的图标拖到或侧的文件夹下。

装置好当前,执行已装置的 MongoDB Compass 利用,会显示如下的界面。

如果是第一次装置,你可能会看到应用提醒窗,如果你不想看,间接关掉即可。在主界面,关上 Advanced Connection Options 你能够设置更具体的参数。

填写好连贯参数后,点击 Connect 按钮,即能够连贯到 MongoDB 数据库。

你能够关上要操作的 Collection,并通过 Insert Document 操作插入新的文档。

在关上的新对话框中,填写要插入的内容。

点击 Insert 按钮插入文档后,能够看到以后 Collection 的数据状况。

当然,通过 Compass 你也能够进行其它的一些操作。

MongoDB Tools

首先须要去官网获取并下载压缩包。

而后解压,并查看解压目录如下:

unzip mongodb-database-tools-macos-x86_64-100.5.3.zip 
Archive:  mongodb-database-tools-macos-x86_64-100.5.3.zip
   creating: mongodb-database-tools-macos-x86_64-100.5.3/
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/LICENSE.md  
   creating: mongodb-database-tools-macos-x86_64-100.5.3/bin/
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongodump  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/bsondump  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongotop  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongoexport  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongoimport  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongostat  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongorestore  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/bin/mongofiles  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/THIRD-PARTY-NOTICES  
  inflating: mongodb-database-tools-macos-x86_64-100.5.3/README.md  
download 20220618 $ cd mongodb-database-tools-macos-x86_64-100.5.3 
mongodb-database-tools-macos-x86_64-100.5.3 20220618 $ ls
LICENSE.md        README.md        THIRD-PARTY-NOTICES    bin
mongodb-database-tools-macos-x86_64-100.5.3 20220618 $ ls bin
bsondump    mongodump    mongoexport    mongofiles    mongoimport    mongorestore    mongostat    mongotop

bin 目录下,能够看到如下的一些命令行工具。

其中,

  • mongodump 用于以二进制的形式备份并导出 MongoDB 数据库
  • mongorestore 用于将 mongodump 导出的数据恢复到 MongoDB 数据库中
  • bsondump 用于将二进制的导出数据转化为 JSON 格局
  • mongoexport 用于导出 JSON 或 CSV 格局的数据
  • mongoimport 用于导入 JSON 或 CSV 格局的数据
  • mongostat 用于显示 MongoDB 服务实例运行状况的统计信息
  • mongotop 用于显示最耗时的数据读写操作
  • mongofiles 用于操作 MongoDB 中以 GridFS 模式存储文件对象

通过程序代码连贯 MongoDB

如果你是一名程序员,在你开发的利用中应用了 MongoDB 存取数据,那么你免不了通过 MongoDB 数据库驱动来连贯数据库。

MongoDB 的客户端驱动反对大部分以后罕用的开发语言:

如果你想要理解更多的客户端驱动,能够拜访以下的链接:
https://www.mongodb.com/docs/drivers/

更多的时候,咱们可能不会间接应用官网提供客户端连贯并操作数据,而是应用第三方封装好的开发框架进行拜访,如,你可能习惯应用 Spring 技术栈,你能够应用 spring-data-mongodb。

其它的连贯工具

除了以上介绍的 MongoDB 客户端连贯工具外,还有很多工具供你抉择应用,如,

  • 针对 Atlas 的 CLI
  • 针对 BI 的 Connector 等等

据说第三方的 Studio 3T 也很好用,不过它是个商业版。

参考资料

  • MongoDB 官网文档
  • 客户端连贯驱动
  • https://formulae.brew.sh/
  • Docker 官网
  • Mongo Tools 应用阐明
正文完
 0