分布式文档存储数据库之MongoDB基础入门

时间:2024-01-05 18:28:14

  一、MongoDB简介

  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协议开源;

分布式文档存储数据库之MongoDB基础入门

  以上这张图反映了MongoDB和其他数据库的伸缩性和性能以及功能的一些比较;横轴代表数据库的功能,纵轴代表可伸缩性和性能;从上图坐标系可以看到关系型数据sql server/mysql的功能是最强大,但是对于伸缩性和性能来讲也是最低的;对于memcached来讲它的的伸缩性和性能是最好的,因为它不需与持久化存储数据,所有数据都在内存,同时它的功能也非常简陋,所以memcached的性能是最好的,但是功能是最简陋的;对于k/v键值数据库来讲,它的性能和伸缩性要略小于memcached,功能要比memcached要略多一点;对于MongoDB来讲,它要比memcached的性能和伸缩性要略小,但功能比它强很多,性能同k/v数据库不相上下,比关系型数据库的可伸缩性和性能都要高很多,同时对于关系型数据库的功能也相差不多;从上面的图可以看到mongodb是性能和扩展性要优于关系型数据,同时功能上也不输关系型数据库多少;正是因为mongodb的这些特性,相比其他nosql,MongoDB的使用量是排在第一的;

分布式文档存储数据库之MongoDB基础入门

  MongoDB和关系型数据

分布式文档存储数据库之MongoDB基础入门

  以上这张图主要对比了mongodb和关系型数据库中的数据库、表、行相关概念;在mongdb中的数据库和关系型数据库中的数据库类似,都是用来存放多张表格,但在mongodb中,没有表的概念,只有collection(对文档的集合);对于关系型数据库中的行,就相当于mongodb中的document(文档);在关系型数据库中多行数据组成一张表,多张表组成一个库;而在mongodb中是多个文档组成一个collection,多个collection组成一个库;如下图所示

分布式文档存储数据库之MongoDB基础入门

  MongoDB数据特点

  1、mongodb是基于文档的关系型数据库,使用JSON的方式来存储数据;

  2、schema-free

  3、用c++语言编写,支持全面的索引,不支持事务(支持原子事务,或者说当行文档支持事务),基于内存映射文件,所以支持延迟写入,正因为这些特点,使得mongodb的性能优越;

  4、支持副本机制,自动分片机制;所谓副本机制指当一个集群中的主节点挂掉以后,它能自动发现,并将其他一个从节点自动选举提升为主节点;

  5、查询接口不支持sql,而是用JSON/Javascript表示的灵活的文档查询;

  6、支持map/Reduce机制,它能够将数据map以后再做reduce,支持并行处理;

  7、支持根据位置查找对象;

  二、MongoDB安装

  1、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基础入门

  启动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端口处于监听状态即可;

  2、下载官方二进制包,解压安装

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

分布式文档存储数据库之MongoDB基础入门

  提示:选择要下载的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的安装配置启动就完成了;

  三、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;如下图

分布式文档存储数据库之MongoDB基础入门

  更新操作:语法格式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();