头图

Introduction to MongoDB

MongoDB is a NoSQL database stored in the form of documents. MongoDB is divided into a paid version and a free version, and the cloud service version Atlas and the enterprise premium version need to be paid. The MongoDB community version is open source, and the open source code repository address is:
https://github.com/mongodb/mongo

MongoDB is mainly divided into the following three parts:

  • mongod - database service
  • mongos - shard routing
  • mongo - command line client

MongoDB installation

Homebrew installation

If you are using a MacOS system, one available way is to use the Homebrew software management system to install it. The use and parameters of the brew command are described as follows:

 $ 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

Before installation, it is best to use the following command to update the package repository.

 brew update

If you want to install the default version in the package manager, use the following command to install it.

 brew install mongodb

If you don't know which versions of MongoDB are available, you can use the installation package search command line to search for versions supported by Homebrew, and select the corresponding version to install.

 brew search mongodb

If you are not sure whether you have installed it before, or which version you have installed, you can use the following command to query.

 brew info mongodb

Source code compilation and installation

If you are not using conventional Linux, MacOS, Windows and other operating systems. You can download the source code of MongoDB to install and run after building it.
The detailed build process can refer to the following link:
https://github.com/mongodb/mongo/blob/master/docs/building.md

Offline package installation

If you are using a conventional operating system, under normal circumstances, you only need to directly download the compiled package and install it. The download address of the installation package is:

According to your operating system and CPU model, you can choose to download different versions of the installation package and install it.

  • If your operating system is Redhat, after downloading the .rpm file, use the yum command to install it.
  • If your operating system is Ubuntu, after downloading the .deb file, use the apt-get command to install it.
  • If your operating system is Windows, after downloading the .msi file, click and install it directly.
  • If you are using MacOS, you can only download the .tgz compressed package, decompress it and run the mongod service.

No matter what kind of system you are, in fact, the compressed package in .tgz or .zip format is provided. If you cannot find the installation package of the corresponding operating system, you can choose the compressed package to download and install.

Docker installation

My recommended installation method is to use the Docker image to install and use MongoDB. Because Docker's way of running and managing services is more convenient, the operating environment and the local environment are isolated from each other, which can avoid a lot of mutual interference.

Before using Docker to install monbodb, of course you need to prepare the docker running environment. If you have not installed docker, please refer to the official website to install it, which will not be described in detail here.

If you are using it for personal research, it is recommended that you download and install the Docker Desktop version directly.

After the docker runtime environment is ready, you can use the following command to query the optional MongoDB image.

 $ 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]

I generally choose STARS a relatively high image to install. You need to download the Docker image locally through the docker pull command.

 $ 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

You can use the docker images command to view all Docker images that have been downloaded locally.

 $ 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

If you are using Docker Desktop , you can also see all downloaded images in the Images column of Dashboard.
Docker Desktop Images
Then you can start the MongoDB service using the docker command.

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

In the above command:

  • The --name parameter specifies the name of the running container
  • The -d parameter means run in the background
  • -p 27017:27017 specifies the port of the local machine and the port of the monbod service
  • The last mongo is the name of the mirror

If you want to go to the windower command line for further operations, you can use the following command:

 docker exec -it 4a4df84c4bb959609a5754e0b8a94bcd7c272e42ad819af2dee12b72511e2dc9 /bin/sh

or

 docker exec -it mongodb /bin/sh

If you want to stop running MongoDB, just execute the following command.

 docker stop mongodb

If you don't know which containers are currently running, you can use the docker ps command.

 $ 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

If you want to view the window that has stopped running, you need to add the -a parameter.

 $ 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

If you want to start the stopped mongodb Docker container again, just run the dokcer start command.

 docker start mongodb

Connect to the database

connection string

Before introducing the connection tool, let me introduce the format of the database connection string of MongoDB, which is generally as follows:

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

E.g,

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

Connection tool

There are many tools for connecting to MongoDB. The following are the ones I know.

MongoDB VS Code plugin

If you are using the VS Code IDE tool, you can connect it after installing the IDE plugin .
MongoDB VS Code 插件

Command Line Tools MongoDB Shell

There are also several command-line tools for MongoDB. You can download your favorite tool from the official website . Below I will use mongosh as an example to introduce how to use it.

mongodb-compass-download.png
Like the installation method of MonboDB, you can also use the brew intall mongosh command to install it. If you want to use the latest version mongosh , you can directly download the compressed package and decompress it.
mongosh下载

You can use the wget command to download from the command line, or use your browser's download manager to download.

 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 archive, you can use unzip to decompress.

 $ 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

Go to the decompression directory and use the ls command to view the contents of the directory.

 $ 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

In the bin directory, you can see the mongosh command.

After installation, you can use the help command to view help. or refer to the official documentation

 $ 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.

Use the command format of mongosh + 数据库连接串 to connect to the MongoDB database.

 $ 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>

Then you can use MongoDB commands to manipulate the MongoDB database.

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

MongoDB Compass

First, you need to go to the official website to download the installation package.
mongodb-compass-download.png
If you are using MacOS, after clicking the downloaded installation package, the following interface will pop up. You need to drag the MongoDB Compass icon to the or side of the folder.
mongodb-compass-install.png
After installation, execute the installed MongoDB Compass application, and the following interface will be displayed.
mongodb-compass-main-ui.png
If it is the first time to install, you may see the prompt window, if you don't want to see it, just close it. In the main interface, open Advanced Connection Options you can set more detailed parameters.
mongodb-compass-connect.png
After filling in the connection parameters, click the Connect button to connect to the MongoDB database.
mongodb-compass-connected.png
You can open the Collection you want to operate on and insert a new document through the Insert Document operation.
mongodb-compass-insert.png
In the new dialog that opens, fill in what you want to insert.
mongodb-compass-insert-doc.png
After clicking the Insert button to insert the document, you can see the data of the current Collection.
mongodb-compass-inserted.png
Of course, you can also perform other operations through Compass.

MongoDB Tools

First, you need to go to the official website to obtain and download the compressed package.
mongodb-tools-download.png
Then unzip, and view the unzip directory as follows:

 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

In the bin directory, you can see the following command line tools.
mongodb-tools-list.png
in,

  • mongodump is used to backup and export MongoDB database in binary mode
  • mongorestore is used to restore the data exported by mongodump to the MongoDB database
  • bsondump is used to convert binary export data to JSON format
  • mongoexport is used to export data in JSON or CSV format
  • mongoimport is used to import data in JSON or CSV format
  • mongostat is used to display statistics about the running status of the MongoDB service instance
  • mongotop is used to display the most time-consuming data read and write operations
  • mongofiles is used to store file objects in the form of GridFS in MongoDB

Connect to MongoDB through program code

If you are a programmer and use MongoDB to access data in the application you develop, then you will inevitably connect to the database through the MongoDB database driver.

MongoDB's client driver supports most of the commonly used development languages:
MongoDB Drivers
If you want to learn more about client drivers, you can visit the following links:
https://www.mongodb.com/docs/drivers/

More often, we may not directly use the official client to connect and operate data, but use a third-party packaged development framework for access. For example, you may be accustomed to using the Spring technology stack, you can use spring-data- mongodb .

Other connection tools

In addition to the MongoDB client connection tools introduced above, there are many tools for you to choose from, such as,

It is said that the third-party Studio 3T also works well, but it is a commercial version.

References


popgis
40 声望3 粉丝