One 、MongoDB brief introduction
MongoDB Yes, it is c++ An easy extension of language development , Flexible , High performance , Open source ,schema free Document based nosql database ; So-called nosql It's not just sql It means , It has parts sql Characteristics of , At the same time, it's more than sql Better performance and scalability ; So-called schema free Not too many constraints , We know that there are many constraints and paradigms in relational databases , stay MongoDB There is no , So here schema free It means this ;mongodb Support massive data , Support osx,linux,windows,solaris Of 32 Bit and 64 Bit system , be based on GUN VGPL v3.0 Open source agreement ;
The picture above shows MongoDB Comparison with other databases in terms of scalability, performance and functionality ; The horizontal axis represents the function of the database , The vertical axis represents scalability and performance ; You can see relational data from the above coordinate system sql server/mysql Is the most powerful , But it's also the lowest in terms of scalability and performance ; about memcached In terms of its scalability and performance is the best , Because it doesn't need to store data persistently , All the data is in memory , At the same time, its function is very simple , therefore memcached The performance of is the best , But the function is the most rudimentary ; about k/v Key value database , Its performance and scalability are slightly less than memcached, It's more functional than memcached A little bit more ; about MongoDB Speaking of , It's better than memcached Performance and scalability are slightly smaller , But it's a lot more powerful , The performance is the same as k/v Databases are on a par , It's much more scalable and performance than relational databases , At the same time, the function of relational database is not much different ; You can see from the picture above mongodb It's better performance and scalability than relational data , At the same time, the function of relational database is not input ; Precisely because mongodb These characteristics of , Compared to other nosql,MongoDB The number one usage is ;
MongoDB And relational data
The above picture mainly compares mongodb And databases in relational databases 、 surface 、 Line related concepts ; stay mongdb A database in is similar to a database in a relational database , They are used to store multiple forms , But in mongodb in , There is no concept of table , Only collection( A collection of documents ); For rows in a relational database , Equivalent to mongodb Medium document( file ); In a relational database, multiple rows of data form a table , Multiple tables form a library ; And in the mongodb It's multiple documents that make up a single collection, Multiple collection Form a library ; As shown in the figure below
MongoDB Data characteristics
1、mongodb It's a document based relational database , Use JSON To store data ;
2、schema-free
3、 use c++ Language writing , Support comprehensive index , Unsupported transaction ( Support atomic transactions , In other words, when the line documents support transactions ), Based on memory mapped file , So delay write is supported , Because of these characteristics , bring mongodb Excellent performance ;
4、 Support replica mechanism , Automatic slicing mechanism ; The so-called replica mechanism refers to when the primary node in a cluster fails , It automatically finds out , And the other slave node is automatically elected to the master node ;
5、 Query interface does not support sql, It's about using JSON/Javascript Express flexible document query ;
6、 Support map/Reduce Mechanism , It can take data map Do it later reduce, Support parallel processing ;
7、 Support to find objects by location ;
Two 、MongoDB install
1、yum install
To configure yum Source
[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 ~]#
see mogodb Related introduction
[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 ~]#
install 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 …… Omit part …… 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 ~]#
Edit profile /etc/mongod.conf Configure it to listen on non 127.0.0.1 Address
start-up 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 ~]#
Tips : Please make sure that 27017 The port is listening ;
2、 Download the official binary package , Unpack the installation
Official download address :https://www.mongodb.com/try/download/community;
Tips : Choose what you want to download mongodb Version and running system platform and the corresponding package format , And then click copy link Copy download link address ;
[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]#
Unzip the package , And create a soft link to /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]#
take /usr/local/mongodb/bin/* Soft connect to /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
start-up 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]#
Tips : This way is to use root User start ;
use mongod User start
[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 ~]$
Tips : close mongodb Use --shutdown Options can be ;
mongod Description of relevant 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 ,0.0.0.0 Means to listen to all available addresses of the local computer ;
--port: Used to specify the port to listen to ,mongodb The default is monitor 27017;
--logappend: Specifies that the log is appended to the log file
--fork: Specify the run as background ;
--shutdown: Specify to close mongodb;
Provide configuration file to start
[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
Use the configuration file to start 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 ~]$
Use the configuration file to close 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 ~]$
With yaml Format provides configuration files , Then use its configuration file to start 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 ~]$
Here we are ,mongodb The installation configuration of is started ;
3、 ... and 、MongoDB Based on using
Use mongo Tool connection 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() --- >
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 <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 >
Tips :db.help() It's about looking at db Related operation commands ,db.mycoll.help() Yes view collection Related operation commands ;
Check the database list
> show dbs admin 0.000GB config 0.000GB local 0.000GB > show databases; admin 0.000GB config 0.000GB local 0.000GB >
Check... In the current library collections
> show collections > show tables >
Tips : No display here means that the current library does not have collection;collection It's a collection of multiple documents , amount to mysql The concept of table in ;
Switch Library
> show dbs admin 0.000GB config 0.000GB local 0.000GB > use local switched to db local > show collections startup_log >
Tips : Switch Library , Look again collection, You can see local There is one under the library startup_log Of collection; Here's another point to make , stay mongodb There is no need to create a database in , direct ues that will do , It is the way to create the database in a delayed manner , As long as we switch to a database , In the collection When inserting data , It automatically creates us use The database and our designated collection; As shown below , We're going to create a student database , Use it directly use student Command is enough ;
> 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 >
Tips : Here use student success , But you can't see it by looking directly at the database , because student There is no collection; Only in student In the library collection when , This student The library will create , We'll use it again show dbs The command can see student library ;
View the 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 : Use db.stats() The command can clearly see , The name of the current database ,collections The number of , Database size , Storage size , Index and so on ;
see mongodb Version number of
> db.version() 4.4.1 >
see mongodb Server status
> db.serverStatus()
Check the connection machine address of the current database
> db.getMongo() connection to node01:27017 >
View all of the current database collection Name list
> db.getCollectionNames() [ ] > show dbs admin 0.000GB config 0.000GB local 0.000GB > use config switched to db config > db.getCollectionNames() [ "system.sessions" ] >
establish 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 } >
Tips : establish collection It's similar to creating a database , It's all delayed creation , We just need to go to the corresponding collection Insert document data into , It's automatically generated for us collection; There is also a point to be made here mongodb in , towards collection When inserting document data into , It's arbitrarily inserted , This is it. mongodb and mysql Different points of relational data , because mongodb Yes schema free Characteristics , It's not constrained by how many 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 }) >
see collection Status information
> db.student_info.stats()
Tips : Too much is shown here , The output information is omitted ;
see collection Document information in
> 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" } >
Statistical correspondence collection How many documents are there in
> db.student_info.find().count() 5 >
Inquire about collection The original size of the data in
> db.student_info.dataSize() 418 >
Inquire about collection The original size of the index data in the
> db.student_info.totalIndexSize() 36864 >
Inquire about collection The size of the index plus data compressed storage
> db.student_info.totalSize() 73728 >
Inquire about collection Data compression storage size in
> db.student_info.storageSize() 36864 >
find() Advanced usage
Comparison operation :
$gt, Greater than ; Grammar format :find({field: {$gt: value}})
$gte, Greater than or equal to ;
$lt, Less than ;
$lte, Less than or equal to ;
$ne, It's not equal to ; If you want to query a field equal to a value , Its grammatical form is find({field: value}) that will do ;
> 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" } >
Tips : The above inquiry is based on age Field is greater than the 30 Is the query condition ;
$in, Grammar format :find({field:{$in: [value,value,...]}}), Query the document whose value of a field is in the specified list range
$nin, Query documents whose specified field is not in the specified list , The grammar is the same as $in identical
> 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" } >
Tips : The reason why I put numbers in quotation marks here , Because I used quotation marks when I created the document ,mongodb Recognize it as a string ; Normally, numbers don't need to be quoted , It can be inquired directly ;
Combination conditions :
Logical operations :
$or: Or operations , Grammar format :find({$or:[{<expression>},...]})
$and: And operation
$not: Non operation
$nor: Inverse operation : Returns all documents that do not meet the specified criteria
> 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: Grammar format 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" } >
Tips :boolean The expression can be true perhaps false; It can also be 1 perhaps 0;
$type: The type of the value of the specified field is the document of the specified type , Grammar format :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" } >
Tips :BSON type Is the corresponding type of digital ID , such as double Corresponding 1,string Corresponding 2; Here's the picture
update operation : Grammar format db.mycoll.update(query)
$set: Modify the value of the specified field to the newly specified value : Grammar 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 : Grammar 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 field name , Grammar 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" } >
Tips : When the former condition is {}, Represents the name of all fields in the updated document ;
Delete operation : Grammar format :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" } >
Tips : The default is to delete all documents that meet the specified criteria , We can write a number at the back , To specify the number of documents to delete matching criteria
> 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 >
Tips : Generally, to delete a database, switch to the corresponding database db.dropDatabase();