mongoDB advanced application

Posted by Shibbey on Wed, 06 May 2020 03:09:50 +0200

Replica set introduction

What is a replica set

-MongoDB replication is the process of synchronizing data on multiple servers.

-Replication provides redundant backup of data and stores copies of data on multiple servers, improving data availability,

And can ensure the security of data. -Replication also allows you to recover data from hardware failures and service outages

Principle of replication

Replica set workflow

mongodb requires at least two nodes for replication. One of them is the master node, which is responsible for processing client requests,

The rest are slave nodes, which replicate the data on the master node.

Common collocations of mongodb nodes are:

One master and one slave, one master and many slaves.

The primary node records all operations oplog on it, and the secondary node polls the primary node regularly to obtain these operations,

Then these operations are performed on their own data copies to ensure that the data of the slave node is consistent with that of the master node.

Replica set implementation (continued 1)

Replica Sets

MongoDB has developed a new function replica set in version 1.6, which is more powerful than the previous replication function and adds faults

Automatically switch and repair member nodes, the data between each DB is completely consistent, which greatly reduces the maintenance success.

Using replica set failover is fully automatic.

The structure of Replica Sets is similar to that of a cluster. It can be regarded as a cluster, because it is indeed implemented with a cluster

It works the same:

If one of the nodes fails, the other nodes will immediately send the service

Take over without stopping operation

Replica set implementation

Master slave replication

To achieve data synchronization, you only need to add the "master" parameter when a server starts to indicate the role of this server

It is primary; in addition, add "- slave" and "- source parameters to indicate that the role of this server is slave.

. the advantages of master-slave replication are as follows:

The slave server can perform query work to reduce the access pressure of the master server. -When performing a backup from the server,

Avoid locking the primary server's data during backup.

When the primary server fails, you can quickly switch to the secondary server to reduce downtime.

====================================================================

Specific requirements:

Prepare 3 mongodb servers

Verify replica set configuration

Prepare three virtual machines and configure mongodb replica set with ip of 192.158.4.51192.168.4.52,

192.168.4.53 one of them is the master node, which is responsible for processing client requests, and the rest are slave nodes,

Responsible for replicating data on the primary node,

Realize storage data copy, improve data availability,

Running services

When starting the service, specify the name of the replica set in which the host is located, and use the same replica set name between replica integrators

[root@server51 ~]# mkdir -p /data/db

[root@server51 ~]# mongod --bind_ip 192.168.200.102 --port 27061 --logpath=/var/l
og/mongod.log --replSet rs1 &       //Specify replica set name

[root@server51 ~]# 
[root@server51 ~]# netstat -lnpt|grep mongod
tcp   0  0 192.168.200.102:27078   0.0.0.0:*         LISTEN      6097/mongod         
tcp   0  0 192.168.200.102:27061   0.0.0.0:*         LISTEN      6276/mongod  

[root@server51 ~]# jobs
[1]+  In operation               mongod --bind_ip 192.168.200.102 --port 27061 --logpat
h=/var/log/mongod.log --replSet rs1 &

Step 1: create a mongodb replica set

1) mongodb installation for three hosts (take 4.51 as an example)

[root@mongodb51 ~]# cd mongodb/
[root@mongodb51 mongodb]#  mkdir  /usr/local/mongodb
[root@mongodb51 mongodb]# cd /usr/local/mongodb
[root@mongodb51 mongodb]# cp -r \ 
 /root/mongodb/mongodb-linux-x86_64-rhel70-3.6.3/bin/  .
[root@mongodb51 mongodb]# ls
bin
[root@mongodb51 mongodb]# mkdir etc
[root@mongodb51 mongodb]# mkdir log
[root@mongodb51 mongodb]# mkdir -p data/db
[root@mongodb51 mongodb]# vim etc/mongodb.conf
dbpath=/usr/local/mongodb/data/db/
logpath=/usr/local/mongodb/log/mongodb.log
logappend=true 
fork=true
bind_ip=192.168.4.51
port=27077
replSet=rs1        
//Add rs1 to the replica set. Name rs1 casually. Want to know who is in the same replica set as me. The names of three machines are all rs1

2) Set PATH variable

[root@mongodb51 mongodb]# vim /etc/profile
export PATH=/usr/local/mongodb/bin:$PATH
[root@mongodb51 mongodb]# source  /etc/profile

3) Because the start and stop service name is too long, an alias can be created

Give stop service an alias
[root@mongodb51 mongodb]# alias cmdb='mongod  --dbpath=/usr/local/mongodb/data/db/  --shutdown'

Give the startup service an alias
[root@mongodb51 mongodb]# alias smdb='mongod -f /usr/local/mongodb/etc/mongodb.conf'

4) Start service and connect

[root@mongodb51 ~]# smdb
about to fork child process, waiting until server is ready for connections.
forked process: 5656
child process started successfully, parent exiting

[root@mongodb51 ~]# mongo --host 192.168.4.51 --port 27077
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.4.51:27077/
MongoDB server version: 3.6.3

5) Configure the cluster information. Any one can operate on 51 here

> rs1_config = {        //RS1 ﹣ config start variable names at will. Remember
 _id:"rs1",         //It must be rs1. This is the cluster name of three hosts. This is written in the configuration file
 members:[
 {_id:0,host:"192.168.4.51:27077"},        //_Arbitrary id value, fixed host value
 {_id:1,host:"192.168.4.52:27078"},
 {_id:2,host:"192.168.4.53:27079"}
 ]
 };        //Enter. The following is a success
{
    "_id" : "rs1",
    "members" : [
        {
            "_id" : 0,
            "host" : "192.168.4.51:27077"
        },
        {
            "_id" : 1,
            "host" : "192.168.4.52:27078"
        },
        {
            "_id" : 2,
            "host" : "192.168.4.53:27079"
        }
    ]
}
>

6) Initializing the Replica Sets environment

> rs.initiate(rs1_config)
{
    "ok" : 1,
    "operationTime" : Timestamp(1538187475, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1538187475, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}
rs1:SECONDARY> 
rs1:PRIMARY>            //Prompt PRIMARY, 51 dominated
Working process:

Bull algorithm (with the latest operation or short time to become the master)

Election heartbeat synchronization

rs1_config = {       
 _id:"rs1",         
 members:[
 {_id:0,host:"192.168.4.51:27077",priority:0},       
 {_id:1,host:"192.168.4.52:27078",priority:3},
 {_id:2,host:"192.168.4.53:27079",priority:2}
 ]
 };

7) View on 52 and 53

[root@mongodb52 ~]# mongo --host 192.168.4.52 --port 27078
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.4.52:27078/
MongoDB server version: 3.6.3
...
... 
rs1:SECONDARY>         //Prompt SECONDARY, 52 is from
rs1:SECONDARY> 
rs1:SECONDARY>
[root@192 ~]# mongo --host 192.168.4.53 --port 27079
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.4.53:27079/
MongoDB server version: 3.6.3
...
... 
rs1:SECONDARY>     //Prompt SECONDARY, 53 is from
rs1:SECONDARY>

Note: if the initialization is wrong, reset the variables after restarting the service login, and then reinitialize

8) View status information

rs1:PRIMARY>  rs.status()
...
    "members" : [
        {
            "_id" : 0,
            "name" : "192.168.4.51:27077",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 2295,
            ...
...
        },
        {
            "_id" : 1,
            "name" : "192.168.4.52:27078",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 384,
            ...
          ...
        },
        {
            "_id" : 2,
            "name" : "192.168.4.53:27079",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
...
...

9) Check whether it is a master library

rs1:PRIMARY>  rs .isMaster( )
{
    "hosts" : [
        "192.168.4.51:27077",
        "192.168.4.52:27078",
        "192.168.4.53:27079"
    ],
    "setName" : "rs1",
    "setVersion" : 1,
    "ismaster" : true,        //Main library
    "secondary" : false,
    "primary" : "192.168.4.51:27077",
    "me" : "192.168.4.51:27077",
...
...

10) Validate replica set, synchronize data validation (write data above 51)

rs1:PRIMARY> use gamedb2
switched to db gamedb2
rs1:PRIMARY> db.a.save({name:"yaya",age:75,em:"p@.com"})
WriteResult({ "nInserted" : 1 })

52 view above

[root@mongodb52 ~]# mongo --host 192.168.4.52 --port 27078
rs1:SECONDARY> db.getMongo().setSlaveOk()       //Allow data to be viewed from the library
rs1:SECONDARY> show dbs        //There are game DB2 Libraries
admin    0.000GB
config   0.000GB
ddsdb    0.000GB
gamedb2  0.000GB
local    0.000GB
test     0.000GB

Step 3: switch main database validation

1) Auto switch main database validation
Close 51

[root@mongodb51 ~]# cmdb / / alias previously set
killing process with pid: 5656

View 52 and 53

[root@mongodb52 ~]# mongo --host 192.168.4.52 --port 27078
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.4.52:27078/
MongoDB server version: 3.6.3
...
... 
rs1:PRIMARY>         //52 mainly
rs1:PRIMARY>

[root@mongodb53 ~]# mongo --host 192.168.4.53 --port 27079
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.4.53:27079/
MongoDB server version: 3.6.3
...
... 
rs1:SECONDARY>        //53 from

//Start 51, it will not become the master again, and it will become the slave of 52

[root@mongodb51 ~]# smdb
about to fork child process, waiting until server is ready for connections.
forked process: 6598
child process started successfully, parent exiting
rs1:SECONDARY> rs.isMaster()
{
    "hosts" : [
        "192.168.4.51:27077",
        "192.168.4.52:27078",
        "192.168.4.53:27079"
    ],
    "setName" : "rs1",
    "setVersion" : 1,
    "ismaster" : false,
    "secondary" : true,
    "primary" : "192.168.4.52:27078",
    "me" : "192.168.4.51:27077",
...

==================================
Based on the MongoDB environment, complete the following exercises:
Insert document
consult your documentation
Update document
remove document

Step 1: manage documents

1) Store the system user information / etc/passwd in the user collection under the mdb Library

rs1:PRIMARY> use mdb
switched to db mdb
rs1:PRIMARY> db.user.save({name:"yaya",password:"x",uid:9999,gid:9999,comment:"",homdir:"/home",shell:"/bin/bash"})
WriteResult({ "nInserted" : 1 })
rs1:PRIMARY> exit
bye
[root@mongodb52 ~]#  mongoexport --host 192.168.4.52 --port 27078 -d mdb -c user -f name,password,uid,gid,comment,homdir,shell  --type=csv -o /tmp/user.csv
2018-09-29T11:04:14.967+0800    connected to: 192.168.4.52:27078
2018-09-29T11:04:14.968+0800    exported 1 record
[root@mongodb52 ~]#  cp /etc/passwd /tmp
[root@mongodb52 ~]# sed -i 's/:/,/g'   /tmp/passwd
[root@mongodb52 ~]#  sed -i '$r /tmp/passwd' /tmp/user.csv
[root@mongodb52 ~]# mongoimport --host 192.168.4.52 --port 27078 -d mdb -c user --headerline  --type=csv  /tmp/user.csv
2018-09-29T11:06:08.355+0800    connected to: 192.168.4.52:27078
2018-09-29T11:06:08.363+0800    imported 41 documents

2) View

[root@mongodb52 ~]# mongo --host 192.168.4.52 --port 27078
rs1:PRIMARY> use mdb
switched to db mdb
rs1:PRIMARY> db.user.findOne()
{
    "_id" : ObjectId("5baeeb37ce3cc5539aa21f38"),
    "name" : "yaya",
    "password" : "x",
    "uid" : 9999,
    "gid" : 9999,
    "comment" : "",
    "homdir" : "/home",
    "shell" : "/bin/bash"
}

db.user.find ({condition}, {define the displayed field}) ා specify the query criteria and the displayed field
0 don't show 1 show

rs1:PRIMARY> db.user.find()
{ "_id" : ObjectId("5baeeb37ce3cc5539aa21f38"), "name" : "yaya", "password" : "x", "uid" : 9999, "gid" : 9999, "comment" : "", "homdir" : "/home", "shell" : "/bin/bash" }
...
Type "it" for more            //Press it when this appears, and 20 lines will appear by default

View the name field of each line

rs1:PRIMARY>  db.user.find({},{name:1})        
{ "_id" : ObjectId("5baeeb37ce3cc5539aa21f38"), "name" : "yaya" }
...
...
{ "_id" : ObjectId("5baeec2001805180a1011843"), "name" : "rpc" }
Type "it" for more

Do not look at the "id" field

rs1:PRIMARY> db.user.find({},{_id:0})
{ "name" : "yaya", "password" : "x", "uid" : 9999, "gid" : 9999, "comment" : "", "homdir" : "/home", "shell" : "/bin/bash" }
...
...
{ "name" : "rpc", "password" : "x", "uid" : 32, "gid" : 32, "comment" : "Rpcbind Daemon", "homdir" : "/var/lib/rpcbind", "shell" : "/sbin/nologin" }
Type "it" for more

Don't look at the column of "id", look at the column of "name"

rs1:PRIMARY> db.user.find({},{_id:0,name:1})
{ "name" : "yaya" }
...
...
{ "name" : "rpc" }
Type "it" for more

View the name field starting with a

rs1:PRIMARY> db.user.find({name:/^a/},{_id:0})
{ "name" : "adm", "password" : "x", "uid" : 3, "gid" : 4, "comment" : "adm", "homdir" : "/var/adm", "shell" : "/sbin/nologin" }
{ "name" : "abrt", "password" : "x", "uid" : 173, "gid" : 173, "comment" : "", "homdir" : "/etc/abrt", "shell" : "/sbin/nologin" }
{ "name" : "avahi", "password" : "x", "uid" : 70, "gid" : 70, "comment" : "Avahi mDNS/DNS-SD Stack", "homdir" : "/var/run/avahi-daemon", "shell" : "/sbin/nologin" }

Show previous row of query results
limit number

rs1:PRIMARY>  db.user.find({name:/^a/},{_id:0}).limit (1)
{ "name" : "adm", "password" : "x", "uid" : 3, "gid" : 4, "comment" : "adm", "homdir" : "/var/adm", "shell" : "/sbin/nologin" }

Display the first line of the name field starting with a

rs1:PRIMARY> db.user.findOne({name:/^a/},{_id:0,name:1,shell:1,uid:1})
{ "name" : "adm", "uid" : 3, "shell" : "/sbin/nologin" }

Skip several lines of display (2 lines)
skip number

rs1:PRIMARY> db.user.find({name:/^a/},{_id:0,name:1,shell:1}).skip (2)
{ "name" : "avahi", "shell" : "/sbin/nologin" }

Default ascending sort
sort field name

rs1:PRIMARY> db.user.find({name:/^a/},{_id:0,name:1,shell:1,uid:1}).sort({uid:1})
{ "name" : "adm", "uid" : 3, "shell" : "/sbin/nologin" }
{ "name" : "avahi", "uid" : 70, "shell" : "/sbin/nologin" }
{ "name" : "abrt", "uid" : 173, "shell" : "/sbin/nologin" }

Descending sort

rs1:PRIMARY> db.user.find({name:/^a/},{_id:0,name:1,shell:1,uid:1}).sort({uid:-1})
{ "name" : "abrt", "uid" : 173, "shell" : "/sbin/nologin" }
{ "name" : "avahi", "uid" : 70, "shell" : "/sbin/nologin" }
{ "name" : "adm", "uid" : 3, "shell" : "/sbin/nologin" }

Show all lines with name field starting with a and uid 3

rs1:PRIMARY> db.user.find({name:/^a/,uid:3},{_id:0,name:1,shell:1,uid:1})
{ "name" : "adm", "uid" : 3, "shell" : "/sbin/nologin" }

3) Expression of condition judgment

$in is in

rs1:PRIMARY> db.user.find({uid:{$in:[1,6,9]}})        //A match with a uid of 1 or 6 or 9

{ "_id" : ObjectId("5baeec2001805180a1011833"), "name" : "bin", "password" : "x", "uid" : 1, "gid" : 1, "comment" : "bin", "homdir" : "/bin", "shell" : "/sbin/nologin" }
{ "_id" : ObjectId("5baeec2001805180a1011838"), "name" : "shutdown", "password" : "x", "uid" : 6, "gid" : 0, "comment" : "shutdown", "homdir" : "/sbin", "shell" : "/sbin/shutdown" }

$nin's not here in

rs1:PRIMARY> db.user.find({uid:{$nin:[1,6,9]}},{_id:0,name:1,uid:1})
{ "name" : "yaya", "uid" : 9999 }
...
...
{ "name" : "saslauth", "uid" : 996 }
Type "it" for more

One of the $or conditions is enough

rs1:PRIMARY> db.user.find({$or:[{name:"root"},{uid:1}]},{_id:0,name:1,uid:1})
{ "name" : "root", "uid" : 0 }
{ "name" : "bin", "uid" : 1 }

4) Regular match, name field starting with a

rs1:PRIMARY> db.user.find({name:/^a/},{_id:0,name:1,uid:1})
{ "name" : "adm", "uid" : 3 }
{ "name" : "abrt", "uid" : 173 }
{ "name" : "avahi", "uid" : 70 }

The objectId object type uses 12 bytes of storage space. Each byte has 2 hexadecimal digits and a total of 24 character strings

0 1 2 3 4 5 6 7 8 9 10 11
Time stamp machine PID counter

5) Numerical comparison

$LT (less than) $lte (less than or equal to) $gt (greater than) $gte (greater than or equal to) $ne (not equal to)

rs1:PRIMARY> db.user.find({uid:{$gte:10,$lte:40}},{_id:0,name:1,uid:1})
{ "name" : "operator", "uid" : 11 }
{ "name" : "games", "uid" : 12 }
{ "name" : "ftp", "uid" : 14 }
{ "name" : "rpc", "uid" : 32 }
{ "name" : "rpcuser", "uid" : 29 }
{ "name" : "ntp", "uid" : 38 }

Match null: you can match a field that does not exist, or you can check whether the field has

rs1:PRIMARY> db.user.save({name:null,uid:null})
WriteResult({ "nInserted" : 1 })

rs1:PRIMARY> db.user.find({name:null})
{ "_id" : ObjectId("5baef385f9f3bf625ea1dbd6"), "name" : null, "uid" : null }

rs1:PRIMARY>  db.user.find({shell:null})    //Indicates that this document has no shell field
{ "_id" : ObjectId("5baef385f9f3bf625ea1dbd6"), "name" : null, "uid" : null }

6) The difference between save and insert

Same point: create a collection when it does not exist and insert a record
difference:

Modify the field value of the document when the field value of save()

When insert() _id field value already exists, discard modifying the document field value

rs1:PRIMARY> db.t1.save({name:"bob",age:19})

rs1:PRIMARY> db.t1.insert({name:"bob",age:19})

rs1:PRIMARY> db.t1.save({_id:7,name:"bob",age:19})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 7 })

rs1:PRIMARY>  db.t1.find()
...
...
{ "_id" : 7, "name" : "bob", "age" : 19 }

rs1:PRIMARY> db.t1.save({_id:7,name:"tom",age:19})        //Modify the previous record directly

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.t1.find()
...
...
{ "_id" : 7, "name" : "tom", "age" : 19 }

rs1:PRIMARY> db.t1.insert({_id:8,name:"tom",age:19})        //Can be saved
WriteResult({ "nInserted" : 1 })

rs1:PRIMARY> db.t1.insert({_id:8,name:"tom",age:19})        //Can't save
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: mdb.t1 index: _id_ dup key: { : 8.0 }"
    }
})

7) Insert multiline document

rs1:PRIMARY> db.t1.insertMany([{name:"xiaojiu"},{name:"laoshi"}])
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5baef526f9f3bf625ea1dbd9"),
        ObjectId("5baef526f9f3bf625ea1dbda")
    ]
}

rs1:PRIMARY> db.t1.find()
...
...
{ "_id" : ObjectId("5baef526f9f3bf625ea1dbd9"), "name" : "xiaojiu" }
{ "_id" : ObjectId("5baef526f9f3bf625ea1dbda"), "name" : "laoshi" }

8) update modification

>db.user.find.update({condition},{Modified fields})

rs1:PRIMARY> db.user.update({name:"root"},{password:"XXX"})  

//If this column is not completely written, there is no other value in this row except for the password row

//Equivalent to deletion (to be complete)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.t1.find({name:"root"})
rs1:PRIMARY> db.user.find({name:"root"})   //Nothing but password:"XXX"

9) Modify the value of the specified field when the $set condition matches (local modification)

rs1:PRIMARY> db.user.update({name:"adm"},{$set:{password:"AAA"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.user.find({name:"adm"})        //Still exists
{ "_id" : ObjectId("5baeec2001805180a1011835"), "name" : "adm", "password" : "AAA", "uid" : 3, "gid" : 4, "comment" : "adm", "homdir" : "/var/adm", "shell" : "/sbin/nologin" }

rs1:PRIMARY> db.user.update({name:/^r/},{$set:{password:"FFF"}})        
//Modify the first line of matching criteria by default

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })    

rs1:PRIMARY> db.user.update({name:/^a/},{$set:{password:"FFF"}},false,true)

//Change all matches

WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

10) $unset delete field of matching document

rs1:PRIMARY> db.user.update({name:"sync"},{$unset:{password:1}})     

//Delete password field
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

11) Array

rs1:PRIMARY> db.user.insert({name:"bob",like:["a","b","c","d","e","f",]})
WriteResult({ "nInserted" : 1 })

$pop

Delete the last element of the array, 1 delete the last one, - 1 delete the first one

rs1:PRIMARY> db.user.update({name:"bob"},{$pop:{like:1}})    

//Delete the last of the first matching article

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.user.update({name:"bob"},{$pop:{like:-1}})    

//Delete the first of the matching first

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

$push add new elements to array

rs1:PRIMARY> db.user.update({name:"bob"},{$push:{like:"Z"}})        //Add to last by default

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.user.update({name:"bob"},{$push:{like:"W"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.user.find({name:"bob"})
{ "_id" : ObjectId("5baef7b2034891a205de2959"), "name" : "bob", "like" : [ "b", "c", "d", "e", "Z", "W" ] }

$addToSet avoid adding repeatedly

rs1:PRIMARY> db.user.update({name:"bob"},{$addToSet:{like:"W"}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

rs1:PRIMARY> db.user.find({name:"bob"})
{ "_id" : ObjectId("5baef7b2034891a205de2959"), "name" : "bob", "like" : [ "b", "c", "d", "e", "Z", "W" ] }

$pull deletes the specified element in the array. If there are two bob's, you can use the definition of "id value" to change name:"bob" to id value

rs1:PRIMARY> db.user.update({name:"bob"},{$pull:{like:"c"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

rs1:PRIMARY> db.user.find({name:"bob"})
{ "_id" : ObjectId("5baef7b2034891a205de2959"), "name" : "bob", "like" : [ "b", "d", "e", "Z", "W" ] }

rs1:PRIMARY> db.user.update({"_id":ObjectId("5afc1a717eff45e9cfc57ed3")},{$push:{like:"S"}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

rs1:PRIMARY>

When the $inc condition matches, the field value is added or subtracted by itself

rs1:PRIMARY> db.user.update({uid:{$lte:10}},{$inc:{uid:2}})         

//Set the field value to add 2, and change the first line by default

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   

rs1:PRIMARY> db.user.update({uid:{$lte:10}},{$inc:{uid:2}},false,true)    

//Set field value to add 2, false,true to all

WriteResult({ "nMatched" : 8, "nUpserted" : 0, "nModified" : 8 })   

rs1:PRIMARY> db.user.update({uid:{$lte:10}},{$inc:{uid:-1}})    

//If the number is negative, it will be 1. The first line will be changed by default

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   

12) Delete document
The difference between remove() and drop()

remove() do not delete indexes when deleting documents

drop() deletes the index while deleting the collection

rs1:PRIMARY> db.t1.remove({})
WriteResult({ "nRemoved" : 6 })

rs1:PRIMARY> db.user.remove({name:"/^a/"})        //Delete records beginning with a
WriteResult({ "nRemoved" : 0 })

rs1:PRIMARY> db.t1.drop()        //Delete set t1
true

Topics: Linux MongoDB shell REST vim