分佈式文檔存儲數據庫之MongoDB基礎入門

  1、MongoDB簡介node

  MongoDB是用c++語言開發的一款易擴展,易伸縮,高性能,開源的,schema free 的基於文檔的nosql數據庫;所謂nosql是指不只僅是sql的意思,它擁有部分sql的特性,同時又比sql的性能和擴展要好;所謂schema free指沒有太多的約束,咱們知道在關係型數據庫中有不少約束和範式,在MongoDB中就沒有,因此這裏的schema free是指這個;mongodb支持海量數據,支持osx,linux,windows,solaris的32位和64位系統,基於GUN VGPL v3.0協議開源;mysql

  以上這張圖反映了MongoDB和其餘數據庫的伸縮性和性能以及功能的一些比較;橫軸表明數據庫的功能,縱軸表明可伸縮性和性能;從上圖座標系能夠看到關係型數據sql server/mysql的功能是最強大,可是對於伸縮性和性能來說也是最低的;對於memcached來說它的的伸縮性和性能是最好的,由於它不需與持久化存儲數據,全部數據都在內存,同時它的功能也很是簡陋,因此memcached的性能是最好的,可是功能是最簡陋的;對於k/v鍵值數據庫來說,它的性能和伸縮性要略小於memcached,功能要比memcached要略多一點;對於MongoDB來說,它要比memcached的性能和伸縮性要略小,但功能比它強不少,性能同k/v數據庫不相上下,比關係型數據庫的可伸縮性和性能都要高不少,同時對於關係型數據庫的功能也相差很少;從上面的圖能夠看到mongodb是性能和擴展性要優於關係型數據,同時功能上也不輸關係型數據庫多少;正是由於mongodb的這些特性,相比其餘nosql,MongoDB的使用量是排在第一的;linux

  MongoDB和關係型數據c++

  以上這張圖主要對比了mongodb和關係型數據庫中的數據庫、表、行相關概念;在mongdb中的數據庫和關係型數據庫中的數據庫相似,都是用來存放多張表格,但在mongodb中,沒有表的概念,只有collection(對文檔的集合);對於關係型數據庫中的行,就至關於mongodb中的document(文檔);在關係型數據庫中多行數據組成一張表,多張表組成一個庫;而在mongodb中是多個文檔組成一個collection,多個collection組成一個庫;以下圖所示web

  MongoDB數據特色sql

  一、mongodb是基於文檔的關係型數據庫,使用JSON的方式來存儲數據;mongodb

  二、schema-freeshell

  三、用c++語言編寫,支持全面的索引,不支持事務(支持原子事務,或者說當行文檔支持事務),基於內存映射文件,因此支持延遲寫入,正由於這些特色,使得mongodb的性能優越;數據庫

  四、支持副本機制,自動分片機制;所謂副本機制指當一個集羣中的主節點掛掉之後,它能自動發現,並將其餘一個從節點自動選舉提高爲主節點;express

  五、查詢接口不支持sql,而是用JSON/Javascript表示的靈活的文檔查詢;

  六、支持map/Reduce機制,它可以將數據map之後再作reduce,支持並行處理;

  七、支持根據位置查找對象;

  2、MongoDB安裝

  一、yum安裝

  配置yum源

[root@node01 ~]# cat /etc/yum.repos.d/mongodb.repo
[mongodb-org]
name = MongoDB Repository
baseurl = https://mirrors.aliyun.com/mongodb/yum/redhat/7/mongodb-org/4.4/x86_64/
gpgcheck = 1
enabled = 1
gpgkey = https://www.mongodb.org/static/pgp/server-4.4.asc
[root@node01 ~]# 

  查看mogodb相關簡介

[root@node01 ~]# yum info mongodb-org
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Available Packages
Name        : mongodb-org
Arch        : x86_64
Version     : 4.4.1
Release     : 1.el7
Size        : 5.9 k
Repo        : mongodb-org
Summary     : MongoDB open source document-oriented database system (metapackage)
URL         : http://www.mongodb.org
License     : SSPL
Description : MongoDB is built for scalability, performance and high availability, scaling from single server
            : deployments to large, complex multi-site architectures. By leveraging in-memory computing, MongoDB
            : provides high performance for both reads and writes. MongoDB’s native replication and automated
            : failover enable enterprise-grade reliability and operational flexibility.
            : 
            : MongoDB is an open-source database used by companies of all sizes, across all industries and for a
            : wide variety of applications. It is an agile database that allows schemas to change quickly as
            : applications evolve, while still providing the functionality developers expect from traditional
            : databases, such as secondary indexes, a full query language and strict consistency.
            : 
            : MongoDB has a rich client ecosystem including hadoop integration, officially supported drivers for
            : 10 programming languages and environments, as well as 40 drivers supported by the user community.
            : 
            : MongoDB features:
            : * JSON Data Model with Dynamic Schemas
            : * Auto-Sharding for Horizontal Scalability
            : * Built-In Replication for High Availability
            : * Rich Secondary Indexes, including geospatial
            : * TTL indexes
            : * Text Search
            : * Aggregation Framework & Native MapReduce
            : 
            : This metapackage will install the mongo shell, import/export tools, other client utilities, server
            : software, default configuration, and systemd service files.

[root@node01 ~]# 

  安裝mongodb-org

[root@node01 ~]# yum install mongodb-org -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package mongodb-org.x86_64 0:4.4.1-1.el7 will be installed
--> Processing Dependency: mongodb-org-tools = 4.4.1 for package: mongodb-org-4.4.1-1.el7.x86_64
--> Processing Dependency: mongodb-org-mongos = 4.4.1 for package: mongodb-org-4.4.1-1.el7.x86_64
……省略部份內容……
Installed:
  mongodb-org.x86_64 0:4.4.1-1.el7                                                                              

Dependency Installed:
  cyrus-sasl.x86_64 0:2.1.26-23.el7                            cyrus-sasl-gssapi.x86_64 0:2.1.26-23.el7        
  cyrus-sasl-plain.x86_64 0:2.1.26-23.el7                      mongodb-database-tools.x86_64 0:100.2.0-1       
  mongodb-org-database-tools-extra.x86_64 0:4.4.1-1.el7        mongodb-org-mongos.x86_64 0:4.4.1-1.el7         
  mongodb-org-server.x86_64 0:4.4.1-1.el7                      mongodb-org-shell.x86_64 0:4.4.1-1.el7          
  mongodb-org-tools.x86_64 0:4.4.1-1.el7                      

Dependency Updated:
  cyrus-sasl-lib.x86_64 0:2.1.26-23.el7                                                                         

Complete!
[root@node01 ~]# 

  編輯配置文件/etc/mongod.conf將其配置爲監聽在非127.0.0.1地址

  啓動mongodb

[root@node01 ~]# systemctl start mongod.service 
[root@node01 ~]# ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                          *:27017                                    *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[root@node01 ~]# 

  提示:啓動後請確保27017端口處於監聽狀態便可;

  二、下載官方二進制包,解壓安裝

  官方下載地址:https://www.mongodb.com/try/download/community

  提示:選擇要下載的mongodb的版本和運行的系統平臺以及對應包的格式,而後點擊copy link複製下載連接地址;

[root@node02 ~]# cd /usr/local/src/
[root@node02 src]# ll
total 0
[root@node02 src]# wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.1.tgz
--2020-11-07 19:59:32--  https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.1.tgz
Resolving fastdl.mongodb.org (fastdl.mongodb.org)... 13.35.121.42, 13.35.121.49, 13.35.121.114, ...
Connecting to fastdl.mongodb.org (fastdl.mongodb.org)|13.35.121.42|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 71253687 (68M) [application/gzip]
Saving to: ‘mongodb-linux-x86_64-rhel70-4.4.1.tgz’

100%[======================================================================>] 71,253,687  2.00MB/s   in 43s    

2020-11-07 20:00:19 (1.57 MB/s) - ‘mongodb-linux-x86_64-rhel70-4.4.1.tgz’ saved [71253687/71253687]

[root@node02 src]# ll
total 69584
-rw-r--r-- 1 root root 71253687 Sep  8 22:55 mongodb-linux-x86_64-rhel70-4.4.1.tgz
[root@node02 src]# 

  解壓包,並建立軟鏈接至/usr/local/mongodb

[root@node02 src]# ll
total 69584
-rw-r--r-- 1 root root 71253687 Sep  8 22:55 mongodb-linux-x86_64-rhel70-4.4.1.tgz
[root@node02 src]# tar xf mongodb-linux-x86_64-rhel70-4.4.1.tgz 
[root@node02 src]# ln -sv /usr/local/src/mongodb-linux-x86_64-rhel70-4.4.1 /usr/local/mongodb
‘/usr/local/mongodb’ -> ‘/usr/local/src/mongodb-linux-x86_64-rhel70-4.4.1’
[root@node02 src]# ll /usr/local/
total 0
drwxr-xr-x. 2 root root  6 Nov  5  2016 bin
drwxr-xr-x. 2 root root  6 Nov  5  2016 etc
drwxr-xr-x. 2 root root  6 Nov  5  2016 games
drwxr-xr-x. 2 root root  6 Nov  5  2016 include
drwxr-xr-x. 2 root root  6 Nov  5  2016 lib
drwxr-xr-x. 2 root root  6 Nov  5  2016 lib64
drwxr-xr-x. 2 root root  6 Nov  5  2016 libexec
lrwxrwxrwx  1 root root 48 Nov  7 20:03 mongodb -> /usr/local/src/mongodb-linux-x86_64-rhel70-4.4.1
drwxr-xr-x. 2 root root  6 Nov  5  2016 sbin
drwxr-xr-x. 5 root root 49 Sep 15 20:33 share
drwxr-xr-x. 3 root root 92 Nov  7 20:03 src
[root@node02 src]# 

  將/usr/local/mongodb/bin/*軟鏈接至/usr/bin/

[root@node02 src]# ln -sv /usr/local/mongodb/bin/* /usr/bin/
‘/usr/bin/install_compass’ -> ‘/usr/local/mongodb/bin/install_compass’
‘/usr/bin/mongo’ -> ‘/usr/local/mongodb/bin/mongo’
‘/usr/bin/mongod’ -> ‘/usr/local/mongodb/bin/mongod’
‘/usr/bin/mongos’ -> ‘/usr/local/mongodb/bin/mongos’
[root@node02 src]# mongo
mongo   mongod  mongos  
[root@node02 src]# mongo

  啓動mongodb

[root@node02 src]# mkdir -p /var/lib/mongo
[root@node02 src]# mkdir -p /var/log/mongodb/
[root@node02 src]# groupadd -g 995 mongod
[root@node02 src]# useradd -u 996 -g mongod mongod
[root@node02 src]# mongod --dbpath=/var/lib/mongo/  --logpath=/var/log/mongodb/mongod.log --bind_ip=0.0.0.0 --port=27017 --logappend --fork 
about to fork child process, waiting until server is ready for connections.
forked process: 1594
child process started successfully, parent exiting
[root@node02 src]# ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                          *:27017                                    *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[root@node02 src]# ps axu |grep mongod
root       1594  4.8  3.8 1555604 72740 ?       Sl   20:33   0:01 mongod --dbpath=/var/lib/mongo/ --logpath=/var/log/mongodb/mongod.log --bind_ip=0.0.0.0 --port=27017 --logappend --fork
root       1634  0.0  0.0 112812   972 pts/0    R+   20:34   0:00 grep --color=auto mongod
[root@node02 src]# 

  提示:這種方式是用root用戶啓動;

  用mongod用戶啓動

[root@node02 src]# mongod --shutdown --dbpath=/var/lib/mongo/  --logpath=/var/log/mongodb/mongod.log --bind_ip=0.0.0.0 --port=27017 --logappend --fork
killing process with pid: 1594
[root@node02 src]# ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[root@node02 src]# chown -R mongod.mongod /var/log/mongodb/                                                     
[root@node02 src]# chown -R mongod.mongod /var/lib/mongo/                                                       
[root@node02 src]# su - mongod
[mongod@node02 ~]$ mongod --dbpath=/var/lib/mongo/  --logpath=/var/log/mongodb/mongod.log --bind_ip=0.0.0.0 --port=27017 --logappend --fork
about to fork child process, waiting until server is ready for connections.
forked process: 1697
child process started successfully, parent exiting
[mongod@node02 ~]$ ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                          *:27017                                    *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[mongod@node02 ~]$ ps aux |grep mongod
root       1671  0.0  0.1 191836  2340 pts/0    S    20:37   0:00 su - mongod
mongod     1672  0.1  0.1 115940  2652 pts/0    S    20:37   0:00 -bash
mongod     1697  6.3  3.7 1555916 69368 ?       Sl   20:37   0:00 mongod --dbpath=/var/lib/mongo/ --logpath=/var/log/mongodb/mongod.log --bind_ip=0.0.0.0 --port=27017 --logappend --fork
mongod     1738  0.0  0.1 155436  1868 pts/0    R+   20:37   0:00 ps aux
mongod     1739  0.0  0.0 112812   972 pts/0    S+   20:37   0:00 grep --color=auto mongod
[mongod@node02 ~]$ 

  提示:關閉mongodb 使用--shutdown選項便可;

  mongod 相關參數說明

  --dbpath:用於指定存放數據的目錄;

  --logpath:用於指定日誌文件;

  --bind_ip:指定監聽的ip地址,0.0.0.0表示監聽本機全部可用地址;

  --port:用於指定監聽的端口,mongodb默認是監聽27017;

  --logappend:指定日誌以追加的方式寫入日誌文件

  --fork:指定運行爲後臺;

  --shutdown:指定關閉mongodb;

  提供配置文件方式啓動

[mongod@node02 ~]$ cat /etc/mongod.conf
dbpath=/var/lib/mongo/
logpath=/var/log/mongodb/mongod.log
logappend=1
port=27017
bind_ip=0.0.0.0
fork=1

  使用配置文件啓動mongodb

[mongod@node02 ~]$ mongod -f /etc/mongod.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 2050
child process started successfully, parent exiting
[mongod@node02 ~]$ ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                          *:27017                                    *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[mongod@node02 ~]$ 

  使用配置文件關閉mongodb

[mongod@node02 ~]$ mongod -f /etc/mongod.conf  --shutdown
killing process with pid: 2050
[mongod@node02 ~]$ ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[mongod@node02 ~]$ 

  以yaml格式提供配置文件,而後使用其配置文件啓動mongodb

[mongod@node02 ~]$ cat /etc/mongod.conf
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

processManagement:
  fork: true

net:
  port: 27017
  bindIp: 0.0.0.0

[mongod@node02 ~]$ ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[mongod@node02 ~]$ mongod -f /etc/mongod.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 2166
child process started successfully, parent exiting
[mongod@node02 ~]$ ss -tnl
State      Recv-Q Send-Q           Local Address:Port                          Peer Address:Port              
LISTEN     0      128                          *:22                                       *:*                  
LISTEN     0      100                  127.0.0.1:25                                       *:*                  
LISTEN     0      128                          *:27017                                    *:*                  
LISTEN     0      128                         :::22                                      :::*                  
LISTEN     0      100                        ::1:25                                      :::*                  
[mongod@node02 ~]$ 

  到此,mongodb的安裝配置啓動就完成了;

  3、MongoDB基礎使用

  使用mongo工具鏈接mongodb

[root@node02 ~]# mongo --host node01
MongoDB shell version v4.4.1
connecting to: mongodb://node01:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ecf71c30-5113-4492-bcae-46f2d781ae59") }
MongoDB server version: 4.4.1
---
The server generated these startup warnings when booting: 
        2020-11-07T20:18:51.467+08:00: ***** SERVER RESTARTED *****
        2020-11-07T20:18:52.481+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2020-11-07T20:18:52.481+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2020-11-07T20:18:52.481+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
---
        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()
---
> 

  查看幫助

> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, 'global' is default
        use <db_name>                set current database
        db.mycoll.find()             list objects in collection mycoll
        db.mycoll.find( { a : 1 } )  list objects in mycoll where a == 1
        it                           result of the last line evaluated; use to further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell
> 

  提示:db.help()是查看有關db相關操做的命令,db.mycoll.help()是查看collection相關操做的命令;

  查看數據庫列表

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
> 

  查看當前庫下的collections

> show collections
> show tables
> 

  提示:這裏沒有顯示錶示當前庫沒有collection;collection是多個文檔的集合,至關於mysql中的表的概念;

  切換庫

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use local
switched to db local
> show collections
startup_log
> 

  提示:切換庫,再次查看collection,就能看到local庫下有一個startup_log的collection;這裏還須要說明一點,在mongodb中數據庫是不須要建立的,直接ues便可,它是採用的延時建立數據庫的方式,只要咱們切換到一個數據庫時,在往collection插入數據時,它自動會建立咱們use的數據庫和咱們指定的collection;以下所示,咱們要建立一個student數據庫,直接使用use student命令便可;

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use student
switched to db student
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> 

  提示:咱們這裏use student成功,可是直接查看數據庫是看不到的,由於student中沒有collection;只有在student庫中有collection時,這個student庫纔會建立,咱們再使用show dbs命令就能看到student庫;

  查看當前所在數據庫

> db
student
> db.getName()
student
> 

  查看當前數據庫狀態信息

> db.stats()
{
        "db" : "student",
        "collections" : 0,
        "views" : 0,
        "objects" : 0,
        "avgObjSize" : 0,
        "dataSize" : 0,
        "storageSize" : 0,
        "totalSize" : 0,
        "indexes" : 0,
        "indexSize" : 0,
        "scaleFactor" : 1,
        "fileSize" : 0,
        "fsUsedSize" : 0,
        "fsTotalSize" : 0,
        "ok" : 1
}
> 

  提示:使用db.stats()命令可以清楚的看到,當前數據庫的名稱,collections的數量,數據庫大小,存儲大小,索引等等信息;

  查看mongodb的版本號

> db.version()
4.4.1
> 

  查看mongodb服務器狀態

> db.serverStatus()

  查看當前數據庫的鏈接機器地址

> db.getMongo()
connection to node01:27017
> 

  查看當前數據庫下的全部collection名稱列表

> db.getCollectionNames()
[ ]
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use config
switched to db config
> db.getCollectionNames()
[ "system.sessions" ]
> 

  建立collection

> use student
switched to db student
> db.stats()
{
        "db" : "student",
        "collections" : 0,
        "views" : 0,
        "objects" : 0,
        "avgObjSize" : 0,
        "dataSize" : 0,
        "storageSize" : 0,
        "totalSize" : 0,
        "indexes" : 0,
        "indexSize" : 0,
        "scaleFactor" : 1,
        "fileSize" : 0,
        "fsUsedSize" : 0,
        "fsTotalSize" : 0,
        "ok" : 1
}
> db.student_info.insert({name: "tom",age: "22",gender: "nan"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin    0.000GB
config   0.000GB
local    0.000GB
student  0.000GB
> show collections
student_info
> db.stats()
{
        "db" : "student",
        "collections" : 1,
        "views" : 0,
        "objects" : 1,
        "avgObjSize" : 64,
        "dataSize" : 64,
        "storageSize" : 20480,
        "indexes" : 1,
        "indexSize" : 20480,
        "totalSize" : 40960,
        "scaleFactor" : 1,
        "fsUsedSize" : 1977794560,
        "fsTotalSize" : 52046860288,
        "ok" : 1
}
> 

  提示:建立collection和建立數據庫相似,它都是採用延時建立的方法,咱們只須要往對應的collection中插入文檔數據,它自動會給咱們生成對應的collection;這裏還須要說明一點在mongodb中,向collection中插入文檔數據時,是任意插入的,這就是mongodb和mysql關係型數據不同的點,由於mongodb有schema free的特色,它不受字段的多少約束;以下

> db.student_info.insert({name: "jerry",age: "26"})
WriteResult({ "nInserted" : 1 })
> db.student_info.insert({name: "xiaoming",age: "24",gender: "M",student_id: "003",score: "84"})
WriteResult({ "nInserted" : 1 })
> db.student_info.insert({name: "xiaohong",age: "34",gender: "nv",student_id: "004",score: "44"})
WriteResult({ "nInserted" : 1 })
> db.student_info.insert({name: "zhangsan",age: "90",gender: "M",student_id: "005",score: "94"})
WriteResult({ "nInserted" : 1 })
> 

  查看collection的狀態信息

> db.student_info.stats() 

  提示:這裏顯示的內容過多,就省略了輸出的信息;

  查看collection中的文檔信息

> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : "22", "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
>

  以美觀方式顯示查詢的文檔內容

> db.student_info.find({name:"tom"}).pretty()
{
        "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"),
        "name" : "tom",
        "age" : "22",
        "gender" : "nan"
}
> 

  統計對應collection中有多少條文檔

> db.student_info.find().count()
5
> 

  查詢collection中數據的原始大小

> db.student_info.dataSize()
418
>

  查詢collection中索引數據的原始大小

> db.student_info.totalIndexSize()
36864
>

  查詢collection中索引加數據壓縮存儲以後的大小

> db.student_info.totalSize()
73728
>

  查詢collection中數據壓縮存儲大小

> db.student_info.storageSize()
36864
> 

  find()高級用法

  比較操做:

    $gt,大於;語法格式:find({field: {$gt: value}})

    $gte,大於等於;

    $lt,小於;

    $lte,小於等於;

    $ne,不等於;若是要查詢某個字段等於某個值,其語法格式爲find({field: value})便可;

> db.student_info.find({age: {$gt: "30"}})
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

  提示:以上查詢是以age字段大於30爲查詢條件;

    $in,語法格式:find({field:{$in: [value,value,...]}}),表示查詢某個字段的值在指定列表範圍的文檔

    $nin,查詢指定字段不在指定列表範圍的文檔,語法同$in相同

> db.student_info.find({age: {$in: ['22','24','26']}})
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : "22", "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
> db.student_info.find({age: {$nin: ['22','24','26']}})
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

  提示:我這裏之因此數字要加引號,是由於我在建立文檔時加了引號,mongodb把它識別成字符串了;正常狀況數字不用加引號,是能夠直接查詢的;

  組合條件:

    邏輯運算:

    $or:或運算,語法格式:find({$or:[{<expression>},...]})

    $and:與運算

    $not:非運算

    $nor:反運算:返回不符合指定條件的全部文檔

> db.student_info.find({$or: [{age:{$gt:'22'}},{age:{$lt:'90'}}]})
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : "22", "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.find({$and: [{age:{$gt:'22'}},{age:{$lt:'90'}}]})
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
> 

  元素查詢:根據指定文檔的字段是否存在進行查詢

    $exists:語法格式find({field:{$exists:<boolean>}})

> db.student_info.find({score:{$exists:true}})
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.find({score:{$exists:0}})
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : "22", "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
> 

  提示:boolean表達式能夠是true或者false;也能夠是1或者0;

    $type:返回指定字段的值的類型爲指定類型的文檔,語法格式:find({field:<BSON type>})

> db.student_info.find({score:{$type:1}})
> db.student_info.find({score:{$type:2}})
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

  提示:BSON type是對應類型的數字標識,好比double對應1,string對應2;以下圖

  更新操做:語法格式db.mycoll.update(query)

    $set:修改指定字段的值爲新指定的值:語法格式update({field: value},{$set:{field:new_value}})

> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : "22", "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.update({name:"tom"},{$set:{age:25}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "gender" : "M", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

    $unset:刪除指定字段:語法格式:update({field:value},{$unset:{field1:value,field2:value,...}})

> db.student_info.update({name:"xiaoming"},{$unset:{gender:"nan"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "student_id" : "003", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.update({name:"xiaoming"},{$unset:{gender:"nan",student_id:"003"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

    $rename:更改字段名,語法格式update({field:value},{$rename:{oldname1:newname,oldname2:newname,...}})

> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "gender" : "nv", "student_id" : "004", "score" : "44" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.update({name:"xiaohong"},{$rename:{gender:"xingbie",student_id:"xuehao"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> 

  提示:當前面的條件爲{},表示更新文檔所有字段名稱;

  刪除操做:語法格式:db.mycoll.remove(<query>,<justone>)

> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
{ "_id" : ObjectId("5fa6c89c391624ebd5fc6bc0"), "name" : "zhangsan", "age" : "90", "gender" : "M", "student_id" : "005", "score" : "94" }
> db.student_info.remove({name:"zhangsan"})
WriteResult({ "nRemoved" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : "26" }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
> db.student_info.update({name:"jerry"},{$set:{age:25}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c308391624ebd5fc6bbc"), "name" : "tom", "age" : 25, "gender" : "nan" }
{ "_id" : ObjectId("5fa6c597391624ebd5fc6bbd"), "name" : "jerry", "age" : 25 }
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
> db.student_info.remove({age:25})
WriteResult({ "nRemoved" : 2 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
> 

  提示:默是刪除符合指定條件的全部文檔,咱們能夠在後面寫一個數字,來指定刪除匹配條件的文檔數量

> db.student_info.find()
{ "_id" : ObjectId("5fa6c84b391624ebd5fc6bbe"), "name" : "xiaoming", "age" : "24", "score" : "84" }
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
> db.student_info.remove({age:{$type:2}},1)
WriteResult({ "nRemoved" : 1 })
> db.student_info.find()
{ "_id" : ObjectId("5fa6c877391624ebd5fc6bbf"), "name" : "xiaohong", "age" : "34", "score" : "44", "xingbie" : "nv", "xuehao" : "004" }
> 

  刪除collection

> db.student_info.drop()
true
> show collections
> 

  刪除數據庫

> db.getName()
student
> db.dropDatabase()
{ "dropped" : "student", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> 

  提示:通常刪除數據庫要切換到對應的數據庫下執行db.dropDatabase();

相關文章
相關標籤/搜索