澳门金沙vipmongodb学习笔记

INSERT INTO osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON DUPLICATEKEY UPDATE view_count=view_count+??,?,?,?,?=visit_count+,ip=?,visit_time=NOW()

MySQL:ON DUPLICATE KEY UPDATE用法避免重复插入数据

启动mongodb

通过mongod启动mongodb服务

  1. mongod参数选项

    [root@primary bin]# ./mongod –help

      -h [ --help ]         帮助信息
      --version             版本信息
      -f [ --config ] arg   配置文件选项
      -v [ --verbose ]      提高内部报告标准输出或记录到logpath配置的日志文件中
      --port                指定服务端口(默认27017)
      --auth                启用验证
      --noauthrun           不启用验证
      --nohttpinterface     关闭http接口,默认关闭27018端口访问
      --fork                以守护进程的方式运行MongoDB,创建服务器进程(后台运行)
      --bind_ip             绑定服务IP,若绑定127.0.0.1,则只能本机访问(默认本地所有IP)
      --maxConns            最大同时连接数 默认2000
      --logpath             指定MongoDB日志文件,注意是指定文件不是目录
      --logappend           使用追加的方式写日志
      --pidfilepath         PID File 的完整路径,如果没有设置,则没有PID文件(pidfilepath=/path/mongod.pid )
      --keyFile             集群的私钥的完整路径,只对于Replica Set 架构有效
      --setParameter        设置参数(mongod --setParameter textSearchEnabled=true)
      --nounixsocket        关闭unix socket 监听
      --unixSocketPrefix    UNIX域套接字替代目录,(默认为 /tmp)
      --sysloglog           
      --cpu                 定期显示CPU的CPU利用率和iowait
      --dbpath              指定数据库路径(默认/data/db/)
      --diaglog             选项 0=off 1=W 2=R 3=both 7=W+some reads
      --directoryperdbeach  数据库将存储在一个单独的目录中
      --ipv6                IPV6(默认关闭)
      --journal             启用日志选项,MongoDB的数据操作将会写入到journal文件夹的文件里
      --journalCommitInterval buffer刷新到JournalFile的时间间隔
      --journalOptions      启用日志诊断选项
      --jsonp               允许JSONP形式通过HTTP访问(有安全影响) 
      --nojournal           禁用日志选项
      --noprealloc          不预先分配存储
      --noscripting         禁用脚本引擎
      --notablescan         不允许表扫描
      --nssize arg (=16)    设置信数据库.ns文件大小(MB)
      --profile             档案参数 0=off 1=slow, 2=all
      --quota               将每个数据库限制到一定数量的文件(8个默认值)
      --quotaFiles          #argnumber of files allowed per db, requires --quota
      --repair              #修复所有db
      --repairpath          指定修复文件路径(defaults to dbpath)
      --rest                开启restful http interface,默认是关闭的(控制restful查询接口)
      --shutdown            关闭服务器进程{db.shutdownServer();}
      --slowms arg (=100)   #value of slow for profile and console log
      --smallfilesuse a     #smaller default file size
      --syncdelay arg (=60) 数据写入磁盘的时间秒数(0=never,不推荐)
      --sysinfo             打印一些诊断系统信息
      --upgrade             如果需要升级数据库
    
    //复制选项:
      --oplogSize arg       设置oplog的大小(MB). default is 5% of disk space 
    
      主/从参数:
      --master              master mode
      --slave               slave mode
      --source              从节点指定主节点的IP和端口 <server:port>
      --only arg            从库指定单一的数据库复制
      --slavedelay          设置从库同步主库的延迟时间
      --autoresync          如果从库与主库同步数据差得多,自动重新同步
    
      Replica set(副本集)选项:
      --replSet arg         设置副本集名称,格式 <setname>[/<optionalseedhostlist>]
      --replIndexPrefetch   默认all,secondary副本集的成员将加载所有索引到内存中或只会加载_id索引[none|_id_only|all]

      分片选项:
      --configsvr           声明这是一个集群的config服务,默认端口27019,默认目录/data/configdb
      --shardsvrdeclare     this is a shard db of a cluster; default port 27018
  1. mongod启动服务

    /mongodb/mongodb/bin/mongod --dbpath=/mongodb/mongodb/bin/db
    /mongodb/mongodb/bin/mongod --dbpath=/mongodb/mongodb/bin/db --rest --port=27017 --fork
    说明:
    默认端口:27017 
    web控制台端口:27017+1000=28017
    http://localhost:28017
    
  2. 参数使用

    --config  将配置放到config文件。
    创建:
    mkdir -p /mongodb/mongodb/config/
    mkdir -p /mongodb/mongodb/config/db
    cp mongod /mongodb/mongodb/config/
    vi c.config
    port=27018
    dbpath=/mongodb/mongodb/config/db
    启动
    mongod --config=/mongodb/mongodb/config/c.config
    登录:
    mongo 127.0.0.1:27018
    

使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL

 

关闭mongodb

    > use admin
    switched to db admin

    > db.shutdownServer()
    Sun Sep  4 02:33:44.407 DBClientCursor::init call() failed
    server should be down...
    Sun Sep  4 02:33:44.408 trying reconnect to 127.0.0.1:27017
    Sun Sep  4 02:33:44.408 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017
    > 

INTO
osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON
DUPLICATEKEY UPDATE view_count=view_count+? ?,?,?,?,? =visit_count+
,ip=?,visit_time=NOW() 使用该语法…

INSERT INTO osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON DUPLICATEKEY UPDATE view_count=view_count+?

INSERT INTO osc_space_visit_records(space,user,visit_count,ip,visit_time) VALUES(?,?,?,?,?) 
ON DUPLICATE KEY UPDATE visit_count=visit_count+1,ip=?,visit_time=NOW()

client访问mongodb

  1. mongo参数选项

    [root@primary bin]# ./mongo --help
    MongoDB shell version: 2.4.9
    usage: ./mongo [options] [db address] [file names (ending in .js)]
    db address can be:
      foo   
      192.169.0.5/foo   
      192.169.0.5:9999/foo
    
    选项:
      --shell                   从命令行运行完一个 .js 文件后,停留在shell中,而不是结束
      --nodb                    不连接数据库方式启动,稍后可以使用 new Mongo() 或 connect() 来建立连接
      --quiet                   安静输出
      --port                    连接端口
      --host                    连接主机
      --eval                    #mongo admin --eval "mongo shell指令“
      -u                        认证用户
      -p                        认证密码
      --authenticationDatabase  //>mongo --authenticationDatabase admin -u testuser -p 
      --authenticationMechanism //(=MONGODB-CR)
      -h [ --help ]             帮助信息
      --version                 //show version information
      --verbose                 -v详细模式,多个v可以增加详细输出,如-vvvv
      --ipv6enable              //IPv6 support (disabled by default)
    
  2. 启动例子

    /mongodb/bin/mongo 127.0.0.1:27017
    [root@primary bin]# /mongodb/bin/mongo 127.0.0.1:27017/zxq -u zxq -p 1234
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27017/zxq
    > 
    > show collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq
    zxq123
    > 
    

 

用户认证

开启安全认证之前,需要有一个管理员用户(admin数据库中的用户为超级管理员

  1. 进入admin数据库中,分配用户

    use admin
    db.help()
    > db.addUser("root","1234")
    {
            "user" : "root",
            "readOnly" : false,
            "pwd" : "fa0450e8c3e5fff6005de2f88559c3d9",
            "_id" : ObjectId("57a4f53cda8f119aa039cf34")
    }
    
  2. 进入用户数据库,分配用户

    use zxq
    db.addUser("zxq","1234")
    db.addUser("zxqread","1234",true) //只读用户
    
    > db.addUser("zxq","1234")
    {
            "user" : "zxq",
            "readOnly" : false,
            "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3",
            "_id" : ObjectId("57a4f607da8f119aa039cf35")
    }
    
  3. 服务端开启安全检查

    停止服务,并安全检查方式启动服务
    mongod --dbpath=./db --port=27017 --auth
    
  4. 客户端连接,此时需要认证

    [root@primary bin]# ./mongo 127.0.0.1:27017/zxq
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27017/zxq
    > show collectionsshow collections
    Sat Aug  6 04:26:15.274 error: {
    "$err" : "not authorized for query on zxq.system.namespaces",
    "code" : 16550
    } at src/mongo/shell/query.js:128
    > 
    此时认证失败
    >use zxq
    >
    > db.auth("zxq","1234")
    1
    > db.auth("zxq","1234")
    1
    
    >use admin
    > db.auth("root","1234")
    1
    > show collections
    system.indexes
    system.users
    > 
    认证方式通过,可以进行其它操作
    
  5. 客户端连接,此时需要认证

    for:mongod dbname -u uname -p password
    
    [root@primary bin]# ./mongo admin -u root -p 1234
    MongoDB shell version: 2.4.9
    connecting to: admin
    
    [root@primary bin]# ./mongo zxq -u zxq -p 1234
    MongoDB shell version: 2.4.9
    connecting to: zxq
    
    **//只读用户测试//**

    [root@primary bin]# ./mongo zxq -u readonly -p 1234
    MongoDB shell version: 2.4.9
    connecting to: zxq
    > db.zxq.insert({"zxq":"zxq"})
    not authorized for insert on zxq.zxq
    > 

 

DB操作命令

db.addUser(userDocument)

    //添加用户
    > db.addUser("zxq","1234")
    {
            "user" : "zxq",
            "readOnly" : false,
            "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3",
            "_id" : ObjectId("57a4f607da8f119aa039cf35")
    }

db.adminCommand(nameOrDocument)

    //切换到admin数据库并执行方法中的命令。
    > db.adminCommand({shutdown : 1})
    { "ok" : 0, "errmsg" : "unauthorized" }
    > 

db.auth(username, password) //用户认证(用户连接)

    > db.auth("zxq","1234")
    1

db.cloneDatabase(fromhost) //从另一个服务器克隆当前选择的数据库

    > db.cloneDatabase("localhost:27017")
    { "clonedColls" : [ "test.zxq", "test.zzz" ], "ok" : 1 }
    > 

    > db
    test
    > show collectionsshow collections
    system.indexes
    zxq
    zzz
    > 

db.copyDatabase(fromdb, todb, fromhost)

    db.copyDatabase('zxq','zxq1')  //本机zxq库copy至zxq1
    > db.copyDatabase('zxq','zxq1','127.0.0.1:27017')  //其它主机zxq库copy至zxq1
    { "ok" : 1 }

    > show dbsshow dbs
    local   0.078125GB
    test0.203125GB
    zxq10.203125GB

    > use zxq1use zxq1
    switched to db zxq1

    > show collectionsshow collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq
    zxq123
    > 

db.createCollection(name, { size : …, capped : …, max : … } )

    db.createCollection("log",{size:1024})
    db.createCollection("zxq", {capped:true, size:100000, max:100})
        //capped当于可以指定一个表可以占用空间的最大空间或指定一个表最大可容纳的记录数
        //指定zxq这个表最大记录数为100,当第101条记录进来时,最早的记录会被自动删除
        //限制它的空间大小为1M,如果超过1M的大小,则会删除最早的记录

    > for(var i=1;i<=101;i++){db.zxq2.insert({name:"a"+i,age:1+i})}
    > db.zxq2.find()
    { "_id" : ObjectId("57a599706c11d61f2a14e10a"), "name" : "a2", "age" : 3 } //age:2记录被自动删除
    { "_id" : ObjectId("57a599706c11d61f2a14e10b"), "name" : "a3", "age" : 4 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10c"), "name" : "a4", "age" : 5 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10d"), "name" : "a5", "age" : 6 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10e"), "name" : "a6", "age" : 7 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10f"), "name" : "a7", "age" : 8 }
    { "_id" : ObjectId("57a599706c11d61f2a14e110"), "name" : "a8", "age" : 9 }

db.currentOp()

    [root@primary zxq]# ./mongo --port=27018
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27018/test
    > db.currentOp()  //显示当前的操作
    {
            "inprog" : [
                    {
                            "opid" : 887864,
                            "active" : true,
                            "secs_running" : 0,
                            "op" : "insert",
                            "ns" : "zxq1.zxq3",
                            "insert" : {

                            },
                            "client" : "127.0.0.1:24327",
                            "desc" : "conn2",
                            "threadId" : "0x7fec8fc71700",
                            "connectionId" : 2,
                            "locks" : {
                                    "^" : "w",
                                    "^zxq1" : "W"
                            },
                            "waitingForLock" : false,
                            "numYields" : 0,
                            "lockStats" : {
                                    "timeLockedMicros" : {

                                    },
                                    "timeAcquiringMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(1)
                                    }
                            }
                    }
            ]
    }

db.dropDatabase()

    //删除当前连接的数据库
    > use zxq1use zxq1
    switched to db zxq1
    > db.dropDatabase()db.dropDatabase()
    { "dropped" : "zxq1", "ok" : 1 }
    > show dbsshow dbs
    local   0.078125GB
    test    0.203125GB
    > 

db.eval(func, args)

    利用db.eval函数可以在MongoDB服务器端执行javascript脚本,这个函数先将给定的
    javascript字符串传递给MongoDB服务器,在服务器上执行,然后返回结果.

    > db.eval("function(name){return 'hello,'+name;}",['refactor'])
    hello,refactor

db.fsyncLock()

db.fsyncUnlock()

    复制数据文件方式数据库:
    直接拷贝数据目录下的一切文件。但是在拷贝过程中必须阻止数据文件发生更改。
    因此需要对数据库加锁,以防止数据写入。

    > db.fsyncLock()
        {
                "info" : "now locked against writes, use db.fsyncUnlock() to unlock",
                "seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
                "ok" : 1
        }
        > 
    上面的命令将阻塞写入操作,并将脏数据刷新到磁盘上,确保数据一致。
    然后,拷贝数据文件到备份目录下

    然后,拷贝数据文件到备份目录下
    cp -R /data/db/* /backup

    文件复制完成后,对数据库进行解锁,允许写操作
    > db.fsyncUnlock()
    > 

    注意: 在执行db.fsyncLock()和db.fsyncUnlock()时,
    不能关闭当前的shell窗口,否则可能无法连接而需要重新启动mongod服务。

    恢复时,确保mongod没有运行,清空数据目录,将备份的数据拷贝到数据目录下,
    然后启动mongod
    # cp -R /backup/* /data/db/
    # mongod -f mongod.conf

db.getCollection(cname)

    //获取文档名称
    > db.getCollection("zxq")
    zxq.zxq

    //文档重命名
    > db.getCollection('zxq').renameCollection('zxqzxq')
    { "ok" : 1 }
    > show collectionsshow collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq123
    zxqzxq  

db.getCollectionNames()

    > db.getCollectionNames()
    [
            "aaa",
            "ddd",
            "system.indexes",
            "system.users",
            "t1",
            "zxq123",
            "zxqzxq"
    ]

    //等同于show collections
    > show collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq123
    zxqzxq
    > 

db.getLastError()

db.getLastErrorObj()

    //db.getLastError()返回上一次错误-如果没有错误则为空
    //db.getLastErrorObj()查看完整的错误结果。
      在没有错误的情况下,db.getLastErrorObj().err应该为空。

    > db.getLastError()
    null

    > db.getLastErrorObj()
    { "n" : 0, "connectionId" : 3, "err" : null, "ok" : 1 }

    > db.getLastErrorObj().err
    null

db.getMongo()

    > db.getMongo()db.getMongo()
    connection to 127.0.0.1
    > 

db.getMongo().setSlaveOk()

    对于replica set 中的secondary 节点默认是不可读的。在写多读少的应用中,
    使用Replica Sets来实现读写分离。通过在连接时指定或者在主库指定slaveOk,
    由Secondary来分担读的压力,Primary只承担写操作。
    如果通过shell访问mongo,要在secondary进行查询。会出现如下错误:
    imageSet:SECONDARY> db.fs.files.find()
    error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

    有两种方法实现从机的查询:
    第一种方法:db.getMongo().setSlaveOk();
    第二种方法:rs.slaveOk();
    但是这种方式有一个缺点就是,下次再通过mongo进入实例的时候,查询仍然会报错,为此可以通过下列方式
    vi ~/.mongorc.js
    增加一行rs.slaveOk();
    这样的话以后每次通过mongo命令进入都可以查询了


    //如果是通过java访问secondary的话则会报下面的异常
    com.mongodb.MongoException: not talking to master and retries used up
    解决的办法很多:
    第一种方法:在java代码中调用dbFactory.getDb().slaveOk();

    第二种方法:在java代码中调用
    dbFactory.getDb().setReadPreference(ReadPreference.secondaryPreferred());
    //在复制集中优先读secondary,如果secondary访问不了的时候就从master中读
    或
    dbFactory.getDb().setReadPreference(ReadPreference.secondary());
    //只从secondary中读,如果secondary访问不了的时候就不能进行查询

    第三种方法:在配置mongo的时候增加slave-ok="true"也支持直接从secondary中读
    <mongo:mongo id="mongo" host="${mongodb.host}" port="${mongodb.port}">
            <mongo:options slave-ok="true"/> 
    </mongo:mongo>

db.getName()

    > db.getName()
    zxq
    //等同db
    > db
    zxq

db.getPrevError()

    查询之前的错误信息
    > db.getPrevError();
    { "err" : null, "n" : 0, "nPrev" : -1, "ok" : 1 }
    > 
    清除错误记录
    > db.resetError();
    { "ok" : 1 }

db.getProfilingLevel()

    mongodb可以通过profile来监控数据,进行优化
    查看当前是否开启profile功能用命令
    返回level等级,值为0|1|2,分别代表意思:
    0代表关闭,1代表记录慢命令,2代表全部
    开始profile功能:
    db.setProfilingLevel(level);  
    #level等级,值同上
    level为1的时候,执行较慢命令默认值为100ms,更改为
    db.setProfilingLevel(level,slowms)
    如db.setProfilingLevel(1,50)这样就更改为50毫秒

    > db.system.profile.find({millis:{$gt:500}}) //所花时间大于500毫秒
    >  
    { "ts" : ISODate("2011-07-23T02:50:13.941Z"), 
    "info" : "query order.order reslen:11022 nscanned:672230  \nquery: { status: 1.0 } nreturned:101
     bytes:11006 640ms", "millis" : 640 }  
    { "ts" : ISODate("2011-07-23T02:51:00.096Z"), 
    "info" : "query order.order reslen:11146 nscanned:672302  \nquery: { status: 1.0, user.uid: 
    { $gt: 1663199.0 } }  nreturned:101 bytes:11130 647ms", "millis" : 647 }  

    注释:
    ts:命令执行时间
    info:命令的内容
        query:代表查询
        order.order: 代表查询的库与集合
        reslen:返回的结果集大小,byte数
        nscanned:扫描记录数量
        nquery:后面是查询条件
        nreturned:返回记录数及用时
        millis:所花时间

db.setProfilingLevel(level,) 0=off 1=slow 2=all

db.getProfilingStatus()

    > db.getProfilingStatus()db.getProfilingStatus()
    { "was" : 0, "slowms" : 100 }

    > db.setProfilingLevel(1,50)
    { "was" : 0, "slowms" : 100, "ok" : 1 }

    > db.getProfilingStatus()
    { "was" : 1, "slowms" : 50 }

db.getReplicationInfo()

    获取当前数据库集群的复制集信息。

db.getSiblingDB(name)

    > db.getSiblingDB("zxq")
    zxq

db.hostInfo()

    > db.hostInfo()
    {
            "system" : {
                    "currentTime" : ISODate("2016-08-06T09:42:13.512Z"),
                    "hostname" : "primary",
                    "cpuAddrSize" : 64,
                    "memSizeMB" : 2910,
                    "numCores" : 1,
                    "cpuArch" : "x86_64",
                    "numaEnabled" : false
            },
            "os" : {
                    "type" : "Linux",
                    "name" : "",
                    "version" : ""
            },
            "extra" : {
                    "versionString" : "Linux version 2.6.32-358.el6.x86_64 
                    (mockbuild@x86-022.build.eng.bos.redhat.com) 
                    (gcc version 4.4.7 20120313 
                    (Red Hat 4.4.7-3) (GCC) ) #1 SMP Tue Jan 29 11:47:41 EST 2013",
                    "libcVersion" : "2.12",
                    "kernelVersion" : "2.6.32-358.el6.x86_64",
                    "cpuFrequencyMHz" : "2497.522",
                    "cpuFeatures" : "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca 
                    cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx rdtscp lm constant_tsc up 
                    rep_good xtopology nonstop_tsc unfair_spinlock pni pclmulqdq monitor ssse3 cx16 
                    sse4_1 sse4_2 popcnt aes xsave avx rdrand hypervisor lahf_lm",
                    "pageSize" : NumberLong(4096),
                    "numPages" : 745116,
                    "maxOpenFiles" : 1024
            },
            "ok" : 1
    }
    > 

db.isMaster()

    //主库状态
    > db.isMaster()
    {
            "ismaster" : true,
            "maxBsonObjectSize" : 16777216,
            "maxMessageSizeBytes" : 48000000,
            "localTime" : ISODate("2016-08-06T09:45:54.651Z"),
            "ok" : 1
    }

db.killOp(opid)

    停止(杀死)在当前库的当前操作,可以用来杀掉长查询

    //诊断1(返回所有与写有关的操作)
    db.currentOp(
       {
         "waitingForLock" : true,
         $or: [
            { "op" : { "$in" : [ "insert", "update", "remove" ] } },
            { "query.findandmodify": { $exists: true } }
        ]
       }
    )


    //诊断2(返回正在运行的操作)
    db.currentOp(
       {
         "active" : true,
         "numYields" : 0,
         "waitingForLock" : false
       }
    )

    //诊断3(在zxq数据库上运行时长超过3S的操作)
    db.currentOp(
       {
         "active" : true,
         "secs_running" : { "$gt" : 3 },
         "ns" : /^zxq\./
       }
    )

    //诊断4(返回创建索引的操作)        
    db.currentOp(
        {
          $or: [
            { op: "query", "query.createIndexes": { $exists: true } },
            { op: "insert", ns: /\.system\.indexes\b/ }
          ]
        }
    )


    //db.currentOp(true) //显示所有会话操作,包括空闲
    > db.currentOp(true)
    {
            "inprog" : [
                    {
                            "opid" : 1526256,
                            "active" : true,
                            "secs_running" : 0,
                            "op" : "insert",
                            "ns" : "zxq.zzzz",
                            "insert" : {

                            },
                            "client" : "127.0.0.1:12599",
                            "desc" : "conn4",
                            "threadId" : "0x7ff3135bd700",
                            "connectionId" : 4,
                            "locks" : {
                                    "^" : "w"
                            },
                            "waitingForLock" : false,
                            "numYields" : 0,
                            "lockStats" : {
                                    "timeLockedMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(57)
                                    },
                                    "timeAcquiringMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(7)
                                    }
                            }
                    }
            ]
    }

    //杀掉操作
    > db.killOp(1526256)
    { "info" : "attempting to kill op" }
    > 

db.listCommands()

    来看当前MongoDB支持的所有命令
    同样可通过运行命令db.runCommand({"listCommands" :1})来查询所有命令

db.loadServerScripts()

    加载在system.js集合中的额所有脚本

db.logout()

    //退出

db.printCollectionStats()

    //显示文档信息
    zzzz
    {
            "ns" : "zxq.zzzz",
            "count" : 8044831,
            "size" : 450510504,
            "avgObjSize" : 55.99999602229059,
            "storageSize" : 582864896,
            "numExtents" : 18,
            "nindexes" : 1,
            "lastExtentSize" : 153874432,
            "paddingFactor" : 1,
            "systemFlags" : 1,
            "userFlags" : 0,
            "totalIndexSize" : 261157792,
            "indexSizes" : {
                    "_id_" : 261157792
            },
            "ok" : 1
    }

db.printReplicationInfo()

db.printShardingStatus()

db.printSlaveReplicationInfo()

    显示复制相关信息

db.removeUser(username)

    //删除用户
    > db.system.users.find()
    { "_id" : ObjectId("57a4f607da8f119aa039cf35"), 
    "user" : "zxq", "readOnly" : false, "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3" }
    { "_id" : ObjectId("57a4f81edb4b33684ccac174"), 
    "user" : "readonly", "readOnly" : true, "pwd" : "853f224e6274e549814cd58e9248293e" }

    > db.removeUser("readonly")
    > db.system.users.find()
    { "_id" : ObjectId("57a4f607da8f119aa039cf35"), 
    "user" : "zxq", "readOnly" : false, "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3" }

db.repairDatabase()

    //dbrepairDatabase,不仅能整理碎片还可以回收磁盘空间
    > db.repairDatabase()
    > db.runCommand({repairDatabase :1})
    > 期间会产生锁,建议关闭应用后再进行此操作
    > 所需要的磁盘剩余空间需求很大
    > 最后一点,这命令能不用最好别用

db.resetError()

    清除错误记录

db.runCommand(cmdObj)

    > db.runCommand({repairDatabase :1})

db.serverStatus()

    //服务器信息
    //修改服务器最大连接数
    > db.serverStatus().connectionsdb
    { "current" : 1, "available" : 818, "totalCreated" : NumberLong(6) }

    修改系统参数:
    vi /etc/rc.local
    ulimit -n 30000

    vi /etc/profile
    ulimit -n 30000
    [root@primary ~]# ulimit -a
    core file size          (blocks, -c) 0
    data seg size           (kbytes, -d) unlimited
    scheduling priority             (-e) 0
    file size               (blocks, -f) unlimited
    pending signals                 (-i) 22892
    max locked memory       (kbytes, -l) 64
    max memory size         (kbytes, -m) unlimited
    open files                      (-n) 30000    //已经生效
    pipe size            (512 bytes, -p) 8
    POSIX message queues     (bytes, -q) 819200
    real-time priority              (-r) 0
    stack size              (kbytes, -s) 10240
    cpu time               (seconds, -t) unlimited
    max user processes              (-u) 22892
    virtual memory          (kbytes, -v) unlimited
    file locks                      (-x) unlimited
    [root@primary ~]# 
    配置文件
    bpath=/mongodb/db/
    logpath=/mongodb/logs/mongod.log
    port=27017
    logappend=true
    fork = true
    directoryperdb=true
    #auth=true
    maxConns=30000
    或
    [root@primary bin]# ./mongod --dbpath=./db --maxConns=20000
    查看服务器最大连接数
    > db.serverStatus().connections;
    { "current" : 2, "available" : 19998, "totalCreated" : NumberLong(3) }
    > 

db.shutdownServer()

    //关闭服务
    > use admin
    switched to db admin
    > db.shutdownServer()
    Sat Aug  6 18:53:47.539 DBClientCursor::init call() failed
    server should be down...
    Sat Aug  6 18:53:47.548 trying reconnect to 127.0.0.1:27017
    Sat Aug  6 18:53:47.548 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017

db.stats()

    //显示当前DB信息
    > db.stats()
    {
            "db" : "test",
            "collections" : 4,
            "objects" : 101,
            "avgObjSize" : 54.53465346534654,
            "dataSize" : 5508,
            "storageSize" : 32768,
            "numExtents" : 5,
            "indexes" : 2,
            "indexSize" : 16352,
            "fileSize" : 201326592,
            "nsSizeMB" : 16,
            "dataFileVersion" : {
                    "major" : 4,
                    "minor" : 5
            },
            "ok" : 1
    }

db.version()

    //显示当前版本
    > db.version()
    2.4.9
    > 

使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL

增、删、改、查

隐式文档创建(文档如果存在,则插入键值,如果不存在,创建文档并插入键值

    > db.zxq.insert({id:1,name:"zxq"})

    //查询文档内容
    > db.zxq.find() 
    { "_id" : ObjectId("57c1c2818ee7bef4894d54b0"), "id" : 1, "name" : "zxq" }

    //求文档条数
    > db.zxq.count()
    1
    > 

    //3.2 新版功能
    db.zxq.insertOne(
       {
          name: "sue",
          age: 19,
          status: "P"
       }
    )

    //插入多条数据
    db.zxq.insertMany(
       [
         { name: "bob", age: 42, status: "A", },
         { name: "ahn", age: 22, status: "A", },
         { name: "xi", age: 34, status: "D", }
       ]
    )
    //例子
    > db.zxq.find()
    > db.zxq.insertMany(
    ...    [
    ...      { name: "bob", age: 42, status: "A", },
    ...      { name: "ahn", age: 22, status: "A", },
    ...      { name: "xi", age: 34, status: "D", }
    ...    ]
    ... )
    {
        "acknowledged" : true,
        "insertedIds" : [
            ObjectId("57c2b637b854b5b8198eebd3"),
            ObjectId("57c2b637b854b5b8198eebd4"),
            ObjectId("57c2b637b854b5b8198eebd5")
        ]
    }
    > db.zxq.find()
    { "_id" : ObjectId("57c2b637b854b5b8198eebd3"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd4"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd5"), "name" : "xi", "age" : 34, "status" : "D" }


    //多个条件查询
    > db.zxq.find({age:{$in:[42,22,34]}})
    { "_id" : ObjectId("57c2b637b854b5b8198eebd3"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd4"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd5"), "name" : "xi", "age" : 34, "status" : "D" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd6"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd7"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd8"), "name" : "xi", "age" : 34, "status" : "D" }
    > 

    > db.zxq.find({_id:{$in:[1,2,3]}})
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    { "_id" : 2, "zxq" : 100 }
    { "_id" : 3, "zxq" : 200 

查询记录

    //查询所有的内容
    > db.users.find( {} )
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }
    > db.users.find()
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }

    //单项查询
    > db.users.find({age:42})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }

    //多条件查询
    > db.users.find({age:{$in:[42,22]}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    > 

$lt 小于

    > db.users.find({age:{$lt:30}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    > 

$or 或条件

    > db.users.find({$or:[{name:"bob" },{age:{$lt:30}}]})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    > 

与条件

    > db.users.find({name:"ahn","age" : 22})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }

    > db.users.find({name:"ahn",$or:[{age:{$lt:30}},{status:"A"}]})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    > 

$gt 大于

    > db.users.find({age:{$gt:15,$lt:35}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }

查询值为Null或不存在的字段

    db.users.insert(
       [
          { "_id" : 900, "name" : null },
          { "_id" : 901 }
       ]
    )

    > db.users.find()
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }
    { "_id" : 900, "name" : null }
    { "_id" : 901 }
    > 

    > db.users.find( { name: null } )
    { "_id" : 900, "name" : null }
    { "_id" : 901 }
    > 

类型筛查(包含值是 null 的 name
字段的文档,亦即条目字段的值是BSON类型中的Null(即 10 ):

    > db.users.find( { name : { $type: 10 } } )
    { "_id" : 900, "name" : null }

存在性筛查

    > db.users.find({name:{$exists:false}})
    { "_id" : 901 }

$where

    > db.zxq.find()
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }

    > db.zxq.find({$where:function(){return this.id==3 && this.name=="c"}})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }
    > 

    > db.zxq.find({$where:function(){ var i=1; return (this.id/i)==3 }})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }


    > db.zxq.find({$where:function(){return (this.id/1)==3 }})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }


    >  db.zxq.find({$where:function(){return ( this.id>1&& this.id<3);}})
    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }
    > 

含有lt

lte gt

gte $eq
< <= > >= =

    > db.zzz.find();
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }

    范围查找案例:
    db.zzz.find({id:{$gte:1,$lte:2}})

    > db.zzz.find({id:{$gte:1,$lte:2}})
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }

OR查询:
in

nin $or

    > var id={"id":{"$in":[1,2]}}
    > db.zzz.find(id)

    $in查询
    > var id={"id":{"$in":[1,2]}}
    > db.zzz.find(id)
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }

    $nin查询
    > db.zzz.find({id:{"$nin":[1,2]}})
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }

    $OR查询
    > var id={"$or":[{"id":1},{"id":2}]}
    > db.zzz.find(id)

    > db.zzz.find({"$or":[{"id":1},{"id":2}]})
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    > 

正则表达式:(类似like)
db.zzz.find({“name”:/a/})

    > db.zzz.find()db.zzz.find()
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    { "_id" : ObjectId("579ebb51e7e548e1d8ec6e23"), "id" : 5, "name" : "abc" }

    > db.zzz.find({"name":/a/})  --带有a的 
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    { "_id" : ObjectId("579ebb51e7e548e1d8ec6e23"), "id" : 5, "name" : "abc" }

    > db.zzz.find({"name":/a$/}) ---以a开头的
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    > 

查询数组

    > var single={"name":"jack",address:["anhui","shanghai","beijing"]}
    > db.mytest.insert(single)
    > db.mytest.find()

    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }

all操作(检索数组中需要包含多个元素,

all数组中必须同时包含的条件)

    > db.mytest.find({"address":{"$all":["anhui","shanghai"]}})

    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }

    > db.mytest.find({"address":{"$all":["anhui","s"]}})

size操作(可以通过

size获取数组的长度,但是$size不能和比较操作符联合使用)

    > db.mytest.find({"address":{"$size":2}})
    > db.mytest.find({"address":{"$size":3}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }

slice操作(通过

slice返回数组中的部分数据。”$slice”:2表示数组中的前两个元素)

    > db.mytest.find({"name":"jack"},{"address":{"$slice":1}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui" ] }

    > db.mytest.find({"name":"jack"},{"address":{"$slice":2}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai" ] }

更新记录

$set 用来指定一个键并更新键值,若键不存在并创建。

$unset 用来删除键

inc修改器

inc可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作

$push
向文档的某个数组类型的键添加一个数组元素,不过滤重复的数据。添加时键存在,要求键值类型必须是数组;键不存在,则创建数组类型的键

$pushAll 指定多个

$addToSet 往一个数组里插入记录

$pop 删除数组内的一个值

$pull 从数组field内删除一个等于value值

pullAll同

pull,可以一次删除数组内的多个值

$rename 修改键值名称

$mul 乘

$min

$max

$currentDate

    > var single=db.zxq.findOne();
    > single
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq" }
    > single.name="zxq3"
    zxq3
    >  db.zxq.update({name:"zxq"},single);
    >  db.zxq.find(); 
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }

    //update更新:
    db.zxq.update(parm1,parm2,parm3,parm4)
    parm1:需要更新的条件
    parm2:更新的对象
    parm3:如果没有符合条件的对象,是否新增一条记录,1(新增),默认值为0
    parm4:如果有多个符合条件的记录,是否全部更新,默认0,如果全部更新取值1 
    语法:
    db.zxq.update({name:"a"},{$set:{age:20}},0,1)  ---更新age键值为20
    db.zxq.update({name:"a"},{$unset:{age:1}},1,1)  ---删除age键
    db.zxq.update({name:"a"},{$inc:{age:1}},0,1)  ---age数据加1
    db.zxq.update({name:"a"},{$inc:{age:-1}},0,1) ---age数据减1

    例如:

set   【语法:db.collection.update( { field: value1 }, {

set: { field1: value2 } } );]

    > db.zxq.update({name:"a"},{$set:{age:20}},0,1)  //0表示没有符合条件的不进行增加
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }

    > db.zxq.update({name:"a"},{$set:{age:20}},1,1)  //1表示没有符合条件的进行增加1行
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    > 

$unset

    > db.zxq.update({id:1},{$unset:{name:1}},0,1)
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }

$inc

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},0,1)   //0表示没有符合条件的不进行增加
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},1,1)  //1表示没有符合条件的进行增加
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" }
    > 

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},1,1)  //有符合条件的id:1进行增加1
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 2, "name" : "zxqzxq" }

    upsert 参数的更新与parm4=1效果一样,在没有符合条件的情况下增加一条记录

    > db.zxq.find({id:6})
    > db.zxq.update({id:6},{$set:{name:"xxxx"}})
    > db.zxq.find({id:6})
    > db.zxq.update({id:6},{$set:{name:"xxxx"}},{upsert:true})
    > db.zxq.find({id:6})
    { "_id" : ObjectId("57c1cebad7f41e4ad2dad410"), "id" : 6, "name" : "xxxx" }


    > db.zxq.update({name:"zxqzxq"},{$inc:{id:2}},1,1)  //有符合条件的id:2进行增加2
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 4, "name" : "zxqzxq" }

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:-2}})   //有符合条件的id:-2进行减少2
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 4, "name" : "zxqzxq" }

    同时更新多条记录
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" }
    //准备更新id:1的所有记录
    > db.zxq.update({id:1},{$set:{name:"zxq"}})
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq" }  //被更新了,增加了键值
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" } //未被更新
    //发现只更新了1条记录

    > db.zxq.update({id:1},{$set:{name:"aaa"}},0,1)  //1表示,如果存在多条,则同时被更新
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "aaa" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "aaa" }

    //{multi:true}同样达到更新多条目的
    > db.zxq.update({id:1},{$set:{name:"xxxx"}},{multi:true})
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "xxxx" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "xxxx" }

$push

    > db.a.find()
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }
    { "_id" : ObjectId("57c1d4c321b1ed73ff5c2968"), "id" : 2, "size" : { "c" : [  3 ] } }
    > 
    > db.a.update({id:2},{$push:{"size.a":1}})
    > db.a.find()
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }
    { "_id" : ObjectId("57c1d4c321b1ed73ff5c2968"), "id" : 2, "size" : { "a" : [  1 ], "c" : [  3 ] } }  //数组类型的键添加一个数组元素

    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }  //向数组中增加元素
    > db.a.update({id:1,name:"a"},{$push:{"size.d":4}},1,0)
    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ], "d" : [  4 ] } }

pushAll  【 语法:{

pushAll: { : [ , , … ] } } 】指定多个值

    > db.a.update({id:1,name:"a"},{$pushAll:{"size.e":[5,6,7]}})
    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ], "d" : [  4 ], "e" : [  5,  6,  7 ] } }
    > 

addToSet  语法:{

addToSet: { : , … } }

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  10,  20 ] }
    > db.a.update({ id:1 },{ $addToSet: {size: [ 30,40] } })
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  10,  20,  [  30,  40 ] ] }
    > 

addToSet和

each 是往一个数组里插入每个记录,并保证元素唯一

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1 }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2 ] }



    //测试数组操作
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2,  3,  4,  5,  6,  7 ] ] }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2, 3,4,5,6,7]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2,  3,  4,  5,  6,  7 ] ] }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2, 3,4,5,6,7,8]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [    [   1,  2,  1,  2,  3,  4,  5, 6,   7 ],    

    [   1,  2,  1,  2,  3,  4,  5,  6,  7,  8 ] ] }
    > 


    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1 }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ] ] }
    > 
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1,3,4,5]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2,  3,  4,  5 ] }
    > 

    //测试数组操作
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 3,4]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 3,4,5,6,7]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4,  5,  6,  7 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [8,9,10]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4,  5,  6,  7,  8,  9,  10 ] }

$pop 只能删除一个值,也就是说只能用1或-1

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2 ] }
    > db.a.update( { id:1} , { $pop : { "size": -1 } } );
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2 ] }
    > 

    >  db.a.update( { id:1} , { $pop : { "size": -1 } } );  //-1从前面删除1个值
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8,  9,  10 ] }
    > db.a.update( { id:1} , { $pop : { "size": 1 } } );    //1从后面删除1个值
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8,  9 ] }
    > db.a.update( { id:1} , { $pop : { "size": 2 } } );    //其它值和1或-1效果一样
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8 ] }
    > db.a.update( { id:1} , { $pop : { "size": -2 } } );   //其它值和1或-1效果一样
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  3,  4,  5,  6,  7,  8 ] }

$pull

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  6,  7,  8 ] }
    > db.a.update( { "id" : 1 } , { $pull : { "size":6} } );
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    > 

$pullAll

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    > db.a.update({id:1},{$pull:{size:[4,8]}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    > db.a.update({id:1},{$pullAll:{size:[4,8]}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    > 

rename   语法:{

rename: { : , : , … } }

    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size1" : [  5,  7 ] }
    > db.a.update({id:1},{$rename:{"size1":"size"}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    > 

    > db.a.insert({id:2,"name": { "first" : "george", "last" : "washington" }})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    { "_id" : ObjectId("57c27c713b5e3ba4c68d0d78"), "id" : 1 }
    { "_id" : ObjectId("57c27c963b5e3ba4c68d0d79"), "id" : 2, "name" : { "first" : "george", "last" : "washington" } }

    > db.a.update({id:2}, {$rename: { "name.first": "name.fname"}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    { "_id" : ObjectId("57c27c713b5e3ba4c68d0d78"), "id" : 1 }
    { "_id" : ObjectId("57c27c963b5e3ba4c68d0d79"), "id" : 2, "name" : { "fname" : "george", "last" : "washington" } }

$mul

    { _id: 1, item: "ABC", price: 10.99 }

    db.zxq.update(
       { _id: 1 },
       { $mul: { price: 1.25 } }
    )

    { _id: 1, item: "ABC", price: 13.7375 }

$min

    > db.zxq.insert({ _id: 1, highScore: 800, lowScore: 200 })
    WriteResult({ "nInserted" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 200 }
    > db.zxq.update( { _id: 1 }, { $min: { lowScore: 150 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $min: { lowScore: 250 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    > 

$max

    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $max: { highScore: 950 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 950, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $max: { highScore: 870 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 950, "lowScore" : 150 }


    > db.a.insert({_id: 1,desc: "crafts",dateEntered: ISODate("2013-10-01 05:00:00"),dateExpired: ISODate("2013-10-01 16:38:16.16")})
    WriteResult({ "nInserted" : 1 })
    > db.a.find()
    { "_id" : 1, "desc" : "crafts", "dateEntered" : ISODate("2013-10-01T05:00:00Z"), "dateExpired" : ISODate("2013-10-01T16:38:16.160Z") }

    > db.a.update({ _id: 1 },{ $max: { dateExpired: new Date("2013-09-30") } })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.a.find()
    { "_id" : 1, "desc" : "crafts", "dateEntered" : ISODate("2013-10-01T05:00:00Z"), "dateExpired" : ISODate("2013-10-01T16:38:16.160Z") }
    > 

$currentDate

    > db.b.insert({ _id: 1, status: "a", lastModified: ISODate("2013-10-02 01:11:18") })
    WriteResult({ "nInserted" : 1 })

    >  db.b.find()
    { "_id" : 1, "status" : "a", "lastModified" : ISODate("2013-10-02T01:11:18Z") }
    > 

    > db.b.update({ _id: 1 }, { $currentDate: { lastModified: true, "cancellation.date": { $type: "timestamp" }  }, 


    $set: { status: "D", "cancellation.reason": "user request"  }})

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

    > db.b.find()
    { "_id" : 1, "status" : "D", "lastModified" : ISODate("2016-08-28T06:55:58.745Z"), "cancellation" : 

    { "date" : Timestamp(1472367358, 1), "reason" : "user request" } }
    > 

    > db.b.find()
    { "_id" : 2, "lastModified" : ISODate("2016-08-28T08:47:21.837Z") }

    > db.b.update({ _id:1}, { $currentDate: { lastModified: true}},1,1)
    WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
    > db.b.find()
    { "_id" : 2, "lastModified" : ISODate("2016-08-28T08:47:21.837Z") }
    { "_id" : 1, "lastModified" : ISODate("2016-08-28T08:48:01.274Z") }
    >