1、 Introduction to mongodb
Mongodb is a document-based NoSQL database developed with C + + language, which is easy to expand, scale, high-performance, open source, schema free. The so-called NoSQL means that it not only means SQL, but also has some features of SQL, but also is better than SQL in terms of performance and extension Free means that there are not too many constraints. We know that there are many constraints and paradigms in relational databases, which are not found in mongodb. Therefore, schema free here refers to this. Mongodb supports massive data, supports 32-bit and 64 bit systems of OSX, Linux, windows and Solaris, and is open-source based on gun vgpl V3.0 protocol;
The above figure shows the comparison of the scalability, performance and functions of mongodb and other databases; the horizontal axis represents the function of the database, and the vertical axis represents the scalability and performance; the relational data SQL can be seen from the above coordinate system Server / MySQL is the most powerful, but it is also the lowest in terms of scalability and performance; for memcached, its scalability and performance are the best, because it does not need to store data persistently, all data is in memory, and its function is also very simple, so memcached has the best performance, but the function is the most humble; for K / V key value data, it has the best performance In terms of library, its performance and scalability are slightly less than memcached, The function of mongodb is slightly more than that of memcached. For mongodb, its performance and scalability are slightly smaller than that of memcached, but the function is much stronger than it. The performance of mongodb is similar to that of K / V database, and the scalability and performance of relational database are much higher than that of relational database. As can be seen from the above figure, mongodb is performance and extension Because of these features of mongodb, compared with other nosqls, the usage of mongodb ranks first;
Mongodb and relational data
The above figure mainly compares the concepts of database, table and row in mongodb and relational database; the database in mongdb is similar to that in relational database, which is used to store multiple tables, but in mongodb, there is no concept of table, only collection (collection of documents); for the row in relational database, it is equivalent to document in mongodb In relational database, multiple rows of data form a table, and multiple tables form a library; in mongodb, multiple documents form a collection and multiple collections form a library, as shown in the figure below
Mongodb data features
1. Mongodb is a document based relational database, which uses JSON to store data;
2、schema-free
3. Written in C + + language, it supports comprehensive index, does not support transactions (supports atomic transactions, or the line document supports transactions), and supports delayed writing based on memory mapped files. Because of these characteristics, mongodb has superior performance;
4. The so-called replica mechanism refers to that when the master node in a cluster is down, it can automatically discover and promote another slave node to be the master node automatically;
5. The query interface does not support SQL, but a flexible document query represented by JSON / JavaScript;
6. In the future, reduce / map will support parallel processing;
7. Support searching objects according to location;
2、 Mongodb installation
1. Yum install
Configure Yum source
[[email protected] ~]# 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
[[email protected] ~]#
View related introduction of mogodb
[[email protected] ~]# 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.
[[email protected] ~]#
Install mongodb ORG
[[email protected] ~]# 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
…… Omit part of the content
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!
[[email protected] ~]#
Edit configuration file / etc/ mongod.conf Configure it to listen at addresses other than 127.0.0.1
Start mongodb
[[email protected] ~]# systemctl start mongod.service
[[email protected] ~]# 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 :::*
[[email protected] ~]#
Prompt: after startup, please make sure that port 27017 is in monitoring state;
2. Download the official binary package, unzip and install
Official download address:https://www.mongodb.com/try/download/community;
Tip: select the version of mongodb to download, the running system platform and the format of the corresponding package, and then click Copy link to copy the download link address;
[[email protected] ~]# cd /usr/local/src/
[[email protected] src]# ll
total 0
[[email protected] 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]
[[email protected] src]# ll
total 69584
-rw-r--r-- 1 root root 71253687 Sep 8 22:55 mongodb-linux-x86_64-rhel70-4.4.1.tgz
[[email protected] src]#
Unzip the package and create a soft connection to / usr / local / mongodb
[[email protected] src]# ll
total 69584
-rw-r--r-- 1 root root 71253687 Sep 8 22:55 mongodb-linux-x86_64-rhel70-4.4.1.tgz
[[email protected] src]# tar xf mongodb-linux-x86_64-rhel70-4.4.1.tgz
[[email protected] 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’
[[email protected] 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
[[email protected] src]#
Connect / usr / local / mongodb / bin / * to / usr / bin/
[[email protected] 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’
[[email protected] src]# mongo
mongo mongod mongos
[[email protected] src]# mongo
Start mongodb
[[email protected] src]# mkdir -p /var/lib/mongo
[[email protected] src]# mkdir -p /var/log/mongodb/
[[email protected] src]# groupadd -g 995 mongod
[[email protected] src]# useradd -u 996 -g mongod mongod
[[email protected] 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
[[email protected] 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 :::*
[[email protected] 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
[[email protected] src]#
Tip: this method is started by root user;
Start with mongod user
[[email protected] 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
[[email protected] 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 :::*
[[email protected] src]# chown -R mongod.mongod /var/log/mongodb/
[[email protected] src]# chown -R mongod.mongod /var/lib/mongo/
[[email protected] src]# su - mongod
[[email protected] ~]$ 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
[[email protected] ~]$ 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 :::*
[[email protected] ~]$ 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
[[email protected] ~]$
Tip: close mongodb and use the — shutdown option;
Description of mongod related parameters
–Dbpath: used to specify the directory where the data is stored;
–Logpath: used to specify the log file;
–bind_ IP: specify the IP address to listen to, 0.0.0.0 means to listen to all available addresses of the machine;
–Port: used to specify the port for listening. Mongodb monitors 27017 by default;
–Logappend: Specifies that the log is written to the log file as an append
–Fork: specify the running as background;
–Shutdown: specifies to shut down mongodb;
Provide configuration file to start
[[email protected] ~]$ 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
Start mongodb with configuration file
[[email protected] ~]$ 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
[[email protected] ~]$ 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 :::*
[[email protected] ~]$
Shut down mongodb using configuration file
[[email protected] ~]$ mongod -f /etc/mongod.conf --shutdown
killing process with pid: 2050
[[email protected] ~]$ 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 :::*
[[email protected] ~]$
Provide the configuration file in yaml format, and then use its configuration file to start mongodb
[[email protected] ~]$ 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
[[email protected] ~]$ 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 :::*
[[email protected] ~]$ 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
[[email protected] ~]$ 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 :::*
[[email protected] ~]$
At this point, the installation and configuration of mongodb is completed;
3、 Basic usage of mongodb
Using Mongo tool to connect mongodb
[[email protected] ~]# 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()
---
>
view help
> 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 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
>
Tips: db.help () is the command to view DB related operations, db.mycoll.help () is the command to view collection related operations;
View database list
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> show databases;
admin 0.000GB
config 0.000GB
local 0.000GB
>
View collections under the current library
> show collections
> show tables
>
Tip: there is no collection in the current library; collection is a collection of multiple documents, which is equivalent to the concept of table in MySQL;
Switch Library
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use local
switched to db local
> show collections
startup_log
>
Tip: switch the library and check the collection again. You can see a startup under the local library_ In mongodb, the database does not need to be created, but directly ues. It adopts the method of delayed database creation. As long as we switch to a database and insert data into the collection, it will automatically create the database we use and the collection we specify. As shown below, we will create a student T database, use the use student command directly;
> 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
>
Tip: we use student successfully, but we can’t see the database directly because there is no collection in the student. Only when there is collection in the student library, the student library will be created. We can see the student library by using the show DBS command;
View current database
> db
student
> db.getName()
student
>
View current database status information
> 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
}
>
Tips: Using db.stats () the command can clearly see the name of the current database, the number of collections, the size of the database, the storage size, the index and other information;
Check the version number of mongodb
> db.version()
4.4.1
>
View mongodb server status
> db.serverStatus()
View the connection machine address of the current database
> db.getMongo()
connection to node01:27017
>
View the list of all collection names under the current database
> db.getCollectionNames()
[ ]
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use config
switched to db config
> db.getCollectionNames()
[ "system.sessions" ]
>
Create 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
}
>
Tip: creating a collection is similar to creating a database. It adopts the method of delayed creation. We only need to insert the document data into the corresponding collection, and it will automatically generate the corresponding collection for us. Here, we also need to explain that when inserting document data into collection in mongodb, it is arbitrarily inserted, which is the relationship data between mongodb and mysql Because mongodb has the feature of schema free, it is not constrained by the number of fields; as follows
> 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 })
>
View status information for collection
> db.student_info.stats()
Tip: if the content displayed here is too much, the output information will be omitted;
View document information in 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" }
>
Display the query document content in a beautiful way
> db.student_info.find({name:"tom"}).pretty()
{
"_id" : ObjectId("5fa6c308391624ebd5fc6bbc"),
"name" : "tom",
"age" : "22",
"gender" : "nan"
}
>
Count the number of documents in the corresponding collection
> db.student_info.find().count()
5
>
Query the original size of the data in the collection
> db.student_info.dataSize()
418
>
Query the original size of index data in collection
> db.student_info.totalIndexSize()
36864
>
Query the size of the index plus data compressed storage in the collection
> db.student_info.totalSize()
73728
>
Query data compression storage size in collection
> db.student_info.storageSize()
36864
>
Find() advanced usage
Comparison operation:
$GT, greater than; syntax format: find ({field: {$GT: value}})
$GTE, greater than or equal to;
$LT, less than;
$LTE, less than or equal to;
If you want to query a field equal to a value, its syntax format is 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" }
>
Tip: the above query is based on the query condition that the age field is greater than 30;
$in, syntax format: find ({field: {$in: [value, value,…]}}), which is used to query the document whose value of a field is in the specified list range
$Nin is used to query documents whose specified field is not in the specified list range. The syntax is the same as $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" }
>
Tip: the reason why I want to use quotation marks here is that I put quotation marks when I create a document, and mongodb recognizes it as a string. Normally, numbers can be queried directly without quotation marks;
Combination conditions:
Logic operation:
$or: or operation, syntax format: find ({$or:[{},…]})
$and: and operation
$not: non operation
$nor: inverse operation: returns all documents that do not meet the specified conditions
> 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" }
>
Element query: query according to whether the field of the specified document exists
$exists: syntax format find ({field: {$exists:}})
> 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" }
>
Hint: Boolean expression can be true or false, or 1 or 0;
$type: return the value of the specified field. The type is the document of the specified type. Syntax format: find ({field: 0})
> 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" }
>
Prompt: bson type is the digital ID of corresponding type, for example, double corresponds to 1, and string corresponds to 2; as shown in the figure below
Update operations: syntax formatting db.mycoll.update (query)
$set: modify the value of the specified field to the newly specified value: syntax format 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: delete the specified field: syntax format: 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: change the field name, syntax format 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" }
>
Tip: when the previous condition is {}, it means that all field names of the updated document are updated;
Delete operation: syntax format: db.mycoll.remove (,)
> 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" }
>
Tip: the default is to delete all documents that meet the specified conditions. We can write a number after it to specify the number of documents to be deleted
> 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" }
>
Delete collection
> db.student_info.drop()
true
> show collections
>
Delete database
> db.getName()
student
> db.dropDatabase()
{ "dropped" : "student", "ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>
Tip: generally, you should switch to the corresponding database to delete the database db.dropDatabase ();