mongodb学习笔记

来源:互联网 发布:吹笛子软件下载 编辑:程序博客网 时间:2024/06/05 15:21

启动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
  2. 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=28017http://localhost:28017
  3. 参数使用

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

关闭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    > 

client访问mongodb

  1. mongo参数选项

    [root@primary bin]# ./mongo --helpMongoDB shell version: 2.4.9usage: ./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 1234MongoDB shell version: 2.4.9connecting to: 127.0.0.1:27017/zxq> > show collectionsaaadddsystem.indexessystem.userst1zxqzxq123> 

用户认证

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

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

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

    use zxqdb.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/zxqMongoDB shell version: 2.4.9connecting to: 127.0.0.1:27017/zxq> show collectionsshow collectionsSat 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 collectionssystem.indexessystem.users> 认证方式通过,可以进行其它操作
  5. 客户端连接,此时需要认证

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

增、删、改、查

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

    > 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" }    > 

含有ltlte gtgte $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查询:
innin $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" ] }

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

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

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

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

sliceslice返回数组中的部分数据。”$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 用来删除键

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

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

$pushAll 指定多个

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

$pop 删除数组内的一个值

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

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

$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 ] ] }    > 

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

    > 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") }    > 

索引,执行计划

    for (var i=0;i<10000;i++){db.ccc.insert({"name":"a"+i,"age":i+1})}    > db.ccc.count()    214069    > db.ccc.find({age:100})    { "_id" : ObjectId("57c2e2c56da14df0c2b1cc85"), "name" : "a99", "age" : 100 }

创建B-tree索引

    > db.ccc.ensureIndex({age:1})     > db.ccc.find({age:100}).explain()    {        "cursor" : "BtreeCursor age_1",        "isMultiKey" : false,        "n" : 1,        "nscannedObjects" : 1,        "nscanned" : 1,        "nscannedObjectsAllPlans" : 1,        "nscannedAllPlans" : 1,        "scanAndOrder" : false,        "indexOnly" : false,        "nYields" : 0,        "nChunkSkips" : 0,        "millis" : 0,        "indexBounds" : {            "age" : [                [                    100,                    100                ]            ]        },        "server" : "linux:27017"    }

创建符合索引 (1:代表升序, -1:代表降序)

    > db.ccc.ensureIndex({age:1,name:1})      db.ccc.ensureIndex({"age":1,"name":-1})    > db.ccc.find({name:"a0"})    { "_id" : ObjectId("57c2e2c56da14df0c2b1cc22"), "name" : "a0", "age" : 1 }    > db.ccc.find({name:"a0"}).explain()    {        "cursor" : "BtreeCursor name_1",        "isMultiKey" : false,        "n" : 1,        "nscannedObjects" : 1,        "nscanned" : 1,        "nscannedObjectsAllPlans" : 1,        "nscannedAllPlans" : 1,        "scanAndOrder" : false,        "indexOnly" : false,        "nYields" : 0,        "nChunkSkips" : 0,        "millis" : 0,        "indexBounds" : {            "name" : [                [                    "a0",                    "a0"                ]            ]        },        "server" : "linux:27017"    }

唯一索引

    > db.ccc.ensureIndex({"age":1},{"unique":true})    > 

查看索引

    > db.ccc.getIndexes()    [        {            "v" : 1,            "key" : {                "_id" : 1            },            "ns" : "test.ccc",            "name" : "_id_"        },        {            "v" : 1,            "key" : {                "age" : 1            },            "ns" : "test.ccc",            "name" : "age_1"        },        {            "v" : 1,            "key" : {                "name" : 1            },            "ns" : "test.ccc",            "name" : "name_1"        },        {            "v" : 1,            "key" : {                "age" : 1,                "name" : 1            },            "ns" : "test.ccc",            "name" : "age_1_name_1"        }    ]    >     > db.system.indexes.find()  //查看所有索引    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.zxq", "name" : "_id_" }    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.a", "name" : "_id_" }    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.users", "name" : "_id_" }    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.ccc", "name" : "_id_" }    { "v" : 1, "key" : { "age" : 1 }, "ns" : "test.ccc", "name" : "age_1" }    { "v" : 1, "key" : { "name" : 1 }, "ns" : "test.ccc", "name" : "name_1" }    { "v" : 1, "key" : { "age" : 1, "name" : 1 }, "ns" : "test.ccc", "name" : "age_1_name_1" }    > 

删除索引

    删除集合所有索引    db.ccc.dropIndexes();    删除特定索引 (删除id字段升序的索引)    db.ccc.dropIndex({"id":1})    > db.ccc.dropIndex({"age" : 1})    { "nIndexesWas" : 2, "ok" : 1 }    查看索引:    db.ccc.getIndexes()    db.system.indexes.find()    重构索引(慎用)    db.articles.reIndex();    注意:索引排序规则升序:1,降序-1

聚合函数

count

    > db.zxq.count()    1000

distinct

    > db.runCommand({"distinct":"zxq","key":"name"})                "a997",            "a998",            "a999",            "a1000"        ],        "stats" : {            "n" : 1000,            "nscanned" : 1000,            "nscannedObjects" : 1000,            "timems" : 2,            "cursor" : "BasicCursor"        },        "ok" : 1    }    distinct使用    db.xxx.distinct("age")    > db.zzz.distinct("id")    [ 1, 2, 3, 4, 5 ]

group

    select a,b,sum(c) csum from coll where active=1 group by a,b;    db.coll.group({        'key':{            'a':true,            'b':true        },        'cond':{ 'active':1 },        'reduce': function(obj, prev)        {            prev.csum ++        },        'initial':{'csum': 0}    })    db.zxq.group({        'key':{            'id':true,            'name':true        },        'cond':{ 'id':1 },  //cond用于筛选条件        'reduce': function(obj, prev) //obj用于扫描行,prev用于输出结果        {            prev.csum ++        },        'initial':{'csum': 0}   //设定初始值    })    //如下案例    > db.zxq.find({id:1})    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }    { "_id" : ObjectId("57cbc9a0c2993ede6eb62ade"), "id" : 1, "name" : "a1" }    { "_id" : ObjectId("57cbc9a2c2993ede6eb62ec6"), "id" : 1, "name" : "a1" }    { "_id" : ObjectId("57cbc9a5c2993ede6eb632ae"), "id" : 1, "name" : "a1" }    > db.zxq.group({ 'key':{ 'id':true,'name':true },'cond':{'id':1},'initial':{'csum': 0},'reduce': function(obj, prev) { prev.csum ++ } })    [ { "id" : 1000, "name" : "a1000", "csum" : 4 } ]    //写法二,runCommand    db.runCommand({group:        {            ns:"zxq",            key:{id:true,name:true},            initial:{num:0},            $reduce:function(doc,prev){            prev.num++}        }    });    //添加筛选条件    db.zxq.group({key:{id:true,name:true},initial:{num:0},$reduce:function(doc,prev){        prev.num++    },    condition:{id:{$gt:990}}    });    //写法二,添加筛选条件    db.runCommand({group:        {            ns:"zxq",            key:{id:true,name:true},            initial:{num:0},            $reduce:function(doc,prev){            prev.num++},            condition:{id:{$gt:998}}        }    });    //使用函数返回值分组    > db.zxq.group({$keyf:function(doc){return {name:doc.name};},initial:{num:0},$reduce:function(doc,prev){ prev.num++ }, condition:{id:{$gt:997}} });    [        {            "name" : "a998",            "num" : 4        },        {            "name" : "a999",            "num" : 4        },        {            "name" : "a1000",            "num" : 4        }    ]    >     //写法二    db.runCommand({group:        {            ns:"zxq",            $keyf:function(doc){return {name:doc.name};},            initial:{num:0},            $reduce:function(doc,prev){            prev.num++}        }    });    //使用终结器    db.zxq.group({$keyf:function(doc){return {name:doc.name};},initial:{num:0},$reduce:function(doc,prev){        prev.num++    },condition:{id:{$gt:997}},    finalize: function(doc){ doc.count=doc.num;delete doc.num; }    });    [        {            "name" : "a998",            "count" : 4        },        {            "name" : "a999",            "count" : 4        },        {            "name" : "a1000",            "count" : 4        }    ]    >     //写法二    db.runCommand({group:        {            ns:"zxq",            $keyf:function(doc){return {name:doc.name};},            initial:{num:0},            $reduce:function(doc,prev){            prev.num++},condition:{id:{$gt:997}},            finalize: function(doc){ doc.count=doc.num;delete doc.num; }        }    });    {        "retval" : [            {                "name" : "a998",                "count" : 4            },            {                "name" : "a999",                "count" : 4            },            {                "name" : "a1000",                "count" : 4            }        ],        "count" : 12,        "keys" : 3,        "ok" : 1    }

MapReduce

能完成count、distinct、group的所有功能

    db.runCommand(    {        mapreduce:'zxq',        map:function(){emit(this.name.substr(0,3),this);},        reduce:function(key,vals){return vals[0];},  //注意:vals是一个Object对象而不是数组        out:'wq'    });    {        "result" : "wq",        "timeMillis" : 124,        "counts" : {            "input" : 4000,            "emit" : 4000,            "reduce" : 387,            "output" : 99        },        "ok" : 1    }    注意:    1.mapreduce是根据map函数里调用的emit函数的第一个参数来进行分组的    2.仅当根据分组键分组后一个键匹配多个文档,才会将key和文档集合交由reduce函数处理。    db.runCommand(    {        mapreduce:'zxq',        map:function(){emit(this.name.substr(0,3),this);},        reduce:function(key,vals){return 'wq';},         out:'wq'    });     //查看wq表数据    > show collections    a    ccc    system.indexes    users    wq    zxq    > db.wq.find()    { "_id" : "a1", "value" : "wq" }    { "_id" : "a10", "value" : "wq" }    { "_id" : "a11", "value" : "wq" }    { "_id" : "a12", "value" : "wq" }    { "_id" : "a13", "value" : "wq" }    { "_id" : "a14", "value" : "wq" }    { "_id" : "a15", "value" : "wq" }    { "_id" : "a16", "value" : "wq" }    { "_id" : "a17", "value" : "wq" }    { "_id" : "a18", "value" : "wq" }    { "_id" : "a19", "value" : "wq" }    { "_id" : "a2", "value" : "wq" }    { "_id" : "a20", "value" : "wq" }    { "_id" : "a21", "value" : "wq" }    { "_id" : "a22", "value" : "wq" }    { "_id" : "a23", "value" : "wq" }    { "_id" : "a24", "value" : "wq" }    { "_id" : "a25", "value" : "wq" }    { "_id" : "a26", "value" : "wq" }    { "_id" : "a27", "value" : "wq" }    Type "it" for more    //案例二:group的功能    > map = function() { for (var key in this) { emit(key, {count : 1}); }};    > reduce = function(key, emits) { total = 0; for (var i in emits) { total += emits[i].count; } return {"count" : total}; }    > db.runCommand({"mapreduce" : "zxq", "map" : map, "reduce" : reduce,"out":"result"})    {        "result" : "result",        "timeMillis" : 307,        "counts" : {            "input" : 4000,            "emit" : 12000,            "reduce" : 120,            "output" : 3        },        "ok" : 1    }    //结果集    > db.result.find()    { "_id" : "_id", "value" : { "count" : 4000 } }    { "_id" : "id", "value" : { "count" : 4000 } }    { "_id" : "name", "value" : { "count" : 4000 } }

删除记录

    > db.zxq.remove({id:1})    > db.zxq.find()    > db.zxq.deleteOne({id:2})    { "acknowledged" : true, "deletedCount" : 1 }    > db.zxq.find({})    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }    >     > db.zxq.deleteMany({"name" : "a"})    { "acknowledged" : true, "deletedCount" : 1 }    > db.zxq.find({})    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }    > 

游标

创建测试表

    > for (i=1;i<=1000;i++){db.zxq.insert({id:i,name:"a"+i})}

定义游标

    var cursor = db.zxq.find();    while (cursor.hasNext()){obj=cursor.next();print(obj.id);}    //增加函数    > db.zxq.find().limit(3)   //显示前面3行    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f7"), "id" : 2, "name" : "a2" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f8"), "id" : 3, "name" : "a3" }    > db.zxq.find().skip(3).limit(3)  //跳过前面3行,显示3行    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f9"), "id" : 4, "name" : "a4" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626fa"), "id" : 5, "name" : "a5" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626fb"), "id" : 6, "name" : "a6" }    > db.zxq.find().limit(3).sort({id:-1}) //降序排序    { "_id" : ObjectId("57cbbbe7c2993ede6eb62add"), "id" : 1000, "name" : "a1000" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb62adc"), "id" : 999, "name" : "a999" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb62adb"), "id" : 998, "name" : "a998" }    > db.zxq.find().limit(3).sort({id:1}) //升序排序    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f7"), "id" : 2, "name" : "a2" }    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f8"), "id" : 3, "name" : "a3" }    //分页处理    var cursor1 = db.zxq.find().limit(100);    var cursor2 = db.zxq.find().skip(100).limit(100);    var cursor3 = db.zxq.find().skip(200).limit(100);    while (cursor1.hasNext()){obj=cursor1.next();print(obj.id);}    while (cursor2.hasNext()){obj=cursor2.next();print(obj.id);}    while (cursor3.hasNext()){obj=cursor3.next();print(obj.id);}

手动迭代游标

    > var myCursor = db.users.find({status:"A"});    > myCursor    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }    >     > var myCursor = db.users.find({status:"A"});    > myCursor.hasNext()    true    > print(tojson(myCursor.next()))    {        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"),        "name" : "bob",        "age" : 42,        "status" : "A"    }    > print(tojson(myCursor.next()))    {        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"),        "name" : "ahn",        "age" : 22,        "status" : "A"    }    > print(tojson(myCursor.next()))    Sun Aug 28 04:28:24.382 error hasNext: false at src/mongo/shell/query.js:124    >     //游标2    > var myCursor = db.users.find({status:"A"});    > printjson(myCursor.next())    {        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"),        "name" : "bob",        "age" : 42,        "status" : "A"    }    > printjson(myCursor.next())    {        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"),        "name" : "ahn",        "age" : 22,        "status" : "A"    }

GridFs

数据库中存放二进制文件超过16M时,使用GridFs,GridFS在数据库中,默认使用fs.chunks和fs.files来存储文件。其中fs.files集合存放文件的信息,fs.chunks存放文件数据。

    [root@linux bin]# echo "zxq is good" >zxq.txt  //创建文件    [root@linux bin]# cat zxq.txt     zxq is good    [root@linux bin]# ./mongofiles put zxq.txt    //文件传输到数据库中    connected to: 127.0.0.1    added file: { _id: ObjectId('57cc32ac747f6865ca501e58'), filename: "zxq.txt", chunkSize: 262144, uploadDate: new Date(1473000108668), md5: "39c87dd1241d8ab74494d88439b7ad9a", length: 12 }    done!    [root@linux bin]#     > show collections      //查看数据库中文档    a    ccc    fs.chunks    fs.files    result    system.indexes    users    wq    zxq    > db.fs.files.find()   //查看表中的文件信息    { "_id" : ObjectId("57cc32ac747f6865ca501e58"), "filename" : "zxq.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:41:48.668Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }    [root@linux bin]# rm zxq.txt    //删除原始文件    rm: remove regular file `zxq.txt'? yes    [root@linux bin]# cat zxq.txt    cat: zxq.txt: No such file or directory    [root@linux bin]#     [root@linux bin]# ./mongofiles list  //查看数据库中文件    connected to: 127.0.0.1    zxq.txt 12    [root@linux bin]#     [root@linux bin]# ./mongofiles get zxq.txt  //从数据库中取出文件    connected to: 127.0.0.1    done write to: zxq.txt    [root@linux bin]# ls    bsondump  mongod       mongofiles   mongoperf     mongosniff  zxq.txt    db        mongodump    mongoimport  mongorestore  mongostat    mongo     mongoexport  mongooplog   mongos        mongotop    [root@linux bin]# cat zxq.txt     zxq is good    [root@linux bin]#     //传入第二个文件    [root@linux bin]# ./mongofiles put zxq1.txt     connected to: 127.0.0.1    added file: { _id: ObjectId('57cc33e4d3e1c4b92d0e0374'), filename: "zxq1.txt", chunkSize: 262144, uploadDate: new Date(1473000420571), md5: "39c87dd1241d8ab74494d88439b7ad9a", length: 12 }    done!    [root@linux bin]# ./mongofiles list    connected to: 127.0.0.1    zxq.txt 12    zxq1.txt    12    > db.fs.files.find()  //查看数据库中文件信息    { "_id" : ObjectId("57cc32ac747f6865ca501e58"), "filename" : "zxq.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:41:48.668Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }    { "_id" : ObjectId("57cc33e4d3e1c4b92d0e0374"), "filename" : "zxq1.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:47:00.571Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }    //查找带有zxq的文件    [root@linux bin]# ./mongofiles search zxq    connected to: 127.0.0.1    zxq.txt 12    zxq1.txt    12    [root@linux bin]# ./mongofiles search zxq.txt    connected to: 127.0.0.1    zxq.txt 12    [root@linux bin]#     Mongofiles参数说明:    –d 指定数据库 ,默认是fs,Mongofiles list –d testGridfs    -u –p 指定用户名,密码    -h  指定主机    -port 指定主机端口    -c 指定集合名,默认是fs    -t 指定文件的MIME类型,默认会忽略        

journal工作原理

journal文件在MongoDB中的作用相当于redo日志文件在oracle中的作用,它可以在即使服务器意外宕机的情况下,将数据库操作进行重演在64位的机器上,2.0以上版本默认是开启了journal的,但是在32位机器上,或者2.0以下的版本中,默认是不开启journal默认情况下mongodb每100毫秒往journal文件中flush一次数据,不过这是在数据文件和journal文件处于同一磁盘卷上的情况,而如果数据文件和journal文件不在同一磁盘卷上时,默认刷新输出时间是30毫秒。不过这个毫秒值是可以修改的,可修改范围是2~300,值越低,刷新输出频率越高,数据安全度也就越高,但磁盘性能上的开销也更高。   journal文件是以“j._”开头命名的,且是append only的,如果1个journal文件满了1G大小,mongodb就会新创建一个journal文件来使用,一旦某个journal文件所记载的写操作都被使用过了,mongodb就会把这个journal文件删除。通常在journal文件所在的文件夹下,只会存在2~3个journal文件,除非你使用mongodb每秒都写入大量的数据。而使用 smallfiles 这个运行时选项可以将journal文件大小减至128M大小。[root@primary journal]# pwd/mongodb/bin/db/journal[root@primary journal]# ls -ltotal 3145740-rw------- 1 root root 1073741824 Aug  6 19:03 j._0-rw------- 1 root root 1073741824 Aug  4 08:01 prealloc.1-rw------- 1 root root 1073741824 Aug  4 08:01 prealloc.2首先要知道在这个原理中,存在着两个file,两个view。两个file是 data file 和 journal file,两个view是 shared view 和 private view。两个file是对磁盘而言的,而两个view是对内存而言的,下面以图解的方式解释:

启动服务前

启动服务后,MongoDB请求操作系统将Data file映射到Shared view,此时操作系统只管映射这个动作,并不将数据加载到Shared view中,而是由MongoDB在需要时再将数据进行加载到Shared view。

然后,MongoDB再请求操作系统将Shared view映射到Private view,之后MongDB对数据的读写操作都是直接操作的Private view

如果发生了写操作

Private view变脏以后,根据journalCommitInterval的设置,将在一定时间后将写操作往Journal file中复制,这个过程称为“group commit”:

Journal file中记录的是原生的操作(raw operation),这些原生的操作可以使MongoDB完成以下操作:    对文档的插入/更新(document insertion/updates)    对索引的修改(index modifications)    对命名空间文件的修改(changes to the namespace files)这些原生操作告诉了Journal file数据变化发生在Data file的什么位置。至此,MongoDB上发生的写事件可以被认为是安全的了,因为这些写操作已经被记录在了Journal file上,即使服务器掉电了,在下次启动MongoDB时,Journal file上的写操作将会被重演。

接下来,Journal file中记录的写操作会应用在Shared view上:

默认每隔60秒,MongoDB请求操作系统将Shared view刷新输出到Data file:

数据就被写入到数据文件了。这时MongoDB还会将Journal file中已输出到Data file的写操作删除掉(由于MongoDB在将Journal file中写操作放到Shared view时,是通过了一个前指针和一个后指针来操作的,所以MongoDB知道哪些写操作是被放到Shared view了的,哪些没有)。最后,MongoDB还会例行地如一开始一样,将Shared view映射到Private view,以保持一致性(也是防止Private view变得太过于脏了)。

MongoDB 做内存数据库使用

    [root@primary bin]# mkdir /mongodata    [root@primary bin]# mount -t tmpfs -o size=2048M tmpfs /mongodata    [root@primary bin]# df -h    Filesystem            Size  Used Avail Use% Mounted on    /dev/mapper/rootvg-rootlv 93G   53G   36G  60% /    tmpfs                 1.5G   72K  1.5G   1% /dev/shm    /dev/sda1             194M   34M  151M  18% /boot    tmpfs                 2.0G     0  2.0G   0% /mongodata    mongodb参数文件    dbpath=/mongodata    //可以减少开销    nojournal = true    smallFiles = true    noprealloc = true    使用    > show dbs    local   0.078125GB    test    (empty)    > use zxquse zxq    switched to db zxq    > db.zxq.insert({name:"a"})>     >     > db.zxq.find()db.zxq.find()    { "_id" : ObjectId("57a5c68ea9475fc6e6d4cb77"), "name" : "a" }    > 

数据导出方式备份

  1. 创建测试表

    for(var i=1;i<1000;i++){db.t1.insert({name:"a"+i,age:i+1})}
  2. 导出表数据

    mongoexport -h 192.168.111.111:27017 -d zxq -c t1 -o /mongodb/backup/t1.txtconnected to: 192.168.111.111:27017exported 999 records
  3. 删除测试数据文档

    [root@primary bin]# > use zxq[root@primary bin]# > db.t1.drop()[root@primary bin]# ./mongoimport -h 192.168.111.111:27017 -d zxq -c t1 /mongodb/backup/t1.txtconnected to: 192.168.111.111:27017Thu Aug  4 19:51:02.880 check 9 999Thu Aug  4 19:51:02.943 imported 999 objects
  4. 验证数据是否恢复

    [root@primary bin]#> db.t1.count()[root@primary bin]#> 999

搭建主从备份

  1. 开启master服务器

    [administrator@localhost ~]$ ./mongod --dbpath=/mongodb/master/db --master -port 27017 --logpath=/mongodb/master/logs/mongodb.log --fork   --master  标记自己是master服务器。   --port    指定自己的端口,默认是27017   --fork    后台运行启动进程
  2. 开启slave服务器

    [administrator@localhost ~]$ ./mongod --dbpath=/mongodb/slave/db --slave --source=127.0.0.1:27017 --port 27018 --logpath=/mongodb/slave/logs/mongodb.log --fork   --slave:   标记自己是slave服务器   --source:  标记我需要同步的服务器是谁? 指定的ip。   --port:     开启自己的端口,千万不能和master重复。   --fork      后台运行启动进程

副本集=>双机热备

配置参数及启动主从库

  1. master上

    配置文件master.confport=27017dbpath=/mongodb/master/dbreplSet=zxq/127.0.0.1:27018 (zxq为副本名称)启动:[root@primary master]# ./mongod --config=/mongodb/master/master.conf --fork
  2. standby上

    配置文件standby.confport=27018dbpath=/mongodb/standby/dbreplSet=zxq/127.0.0.1:27017 (zxq为副本名称)启动:[root@primary standby]# ./mongod --config=/mongodb/standby/standby.conf 注://如果有第三台port=27019dbpath=/mongodb/standby/dbreplSet=zxq/127.0.0.1:27017,127.0.0.1:27018 (zxq为副本名称)

配置主从同步

  1. 创建过程

    //连接到主admin库[root@primary master]# ./mongo 127.0.0.1:27017/adminMongoDB shell version: 2.4.9connecting to: 127.0.0.1:27017/admin> //运行主从同步配置命令db.runCommand({"replSetInitiate":{ "_id":"zxq", "members":[ {"_id":1,"host":"127.0.0.1:27017"}, {"_id":2,"host":"127.0.0.1:27018"} ]}})注:                 zxq  //副本名称    "_id":1和"_id":2  //两个节点的节点ID,不能冲突
  2. 启动过程日志信息

    主节点日志Thu Aug  4 11:29:11.348 [rsStart] trying to contact 127.0.0.1:27018Thu Aug  4 11:29:11.385 [rsStart] replSet I am 127.0.0.1:27017     //提示本节点信息Thu Aug  4 11:29:11.385 [rsStart] replSet STARTUP2Thu Aug  4 11:29:11.388 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra voteThu Aug  4 11:29:11.390 [rsHealthPoll] replSet member 127.0.0.1:27018 is up  //提示从节点启动 Thu Aug  4 11:29:12.387 [rsSync] replSet SECONDARY//从节点日志Thu Aug  4 11:29:11.408 [rsStart] replSet I am 127.0.0.1:27018Thu Aug  4 11:29:11.408 [rsStart] replSet got config version 1 from a remote, saving locallyThu Aug  4 11:29:11.408 [rsStart] replSet info saving a newer config version to local.system.replsetThu Aug  4 11:29:11.412 [rsStart] replSet saveConfigLocally doneThu Aug  4 11:29:11.412 [rsStart] replSet STARTUP2Thu Aug  4 11:29:11.413 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra voteThu Aug  4 11:29:11.467 [rsSync] ******Thu Aug  4 11:29:11.467 [rsSync] creating replication oplog of size: 2289MB...Thu Aug  4 11:29:11.467 [FileAllocator] allocating new datafile /mongodb/standby/db/local.1, filling with zeroes...Thu Aug  4 11:29:11.500 [FileAllocator] done allocating datafile /mongodb/standby/db/local.1, size: 2047MB,  took 0.033 secs //从节点接收到主节点的数据Thu Aug  4 11:29:11.501 [FileAllocator] allocating new datafile /mongodb/standby/db/local.2, filling with zeroes...Thu Aug  4 11:29:11.531 [FileAllocator] done allocating datafile /mongodb/standby/db/local.2, size: 2047MB,  took 
  3. 检查主备节点是否生效

    > rs.status(){"set" : "zxq","date" : ISODate("2016-08-04T03:31:25Z"),"myState" : 1, "members" : [{"_id" : 1,  //站点ID"name" : "127.0.0.1:27017","health" : 1,"state" : 1,"stateStr" : "PRIMARY",  //主节点"uptime" : 415,"optime" : Timestamp(1470281344, 1),"optimeDate" : ISODate("2016-08-04T03:29:04Z"),"self" : true},{"_id" : 2, //站点ID"name" : "127.0.0.1:27018","health" : 1,"state" : 2,"stateStr" : "SECONDARY", //从节点"uptime" : 134,"optime" : Timestamp(1470281344, 1),"optimeDate" : ISODate("2016-08-04T03:29:04Z"),"lastHeartbeat" : ISODate("2016-08-04T03:31:25Z"),"lastHeartbeatRecv" : ISODate("2016-08-04T03:31:25Z"),"pingMs" : 0,"syncingTo" : "127.0.0.1:27017"}],"ok" : 1}//备用节点[root@primary standby]# ./mongo 127.0.0.1:27018MongoDB shell version: 2.4.9connecting to: 127.0.0.1:27018/testzxq:SECONDARY> zxq:SECONDARY>  //已经是备用节点信息
  4. 添加仲裁节点

    创建vote目录,复制mongod、mongo到目录,并创建db目录//创建仲裁节点的配置问题[root@primary vote]# vi vote.conf port=27019dbpath=/mongodb/vote/db//启动仲裁节点[root@primary vote]# ./mongod --config=./vote.conf --fork//在主节点上执行添加仲裁节点的命令rs.addArb("127.0.0.1:27019")  //告诉主从27019是仲裁节点
  5. 仲裁添加完成后日志信息

    27019上日志(仲裁节点)Thu Aug  4 11:41:28.291 [conn3] end connection 127.0.0.1:27460 (2 connections now open)Thu Aug  4 11:41:28.418 [rsHealthPoll] replSet member 127.0.0.1:27017 is upThu Aug  4 11:41:28.418 [rsHealthPoll] replSet member 127.0.0.1:27017 is now in state PRIMARY//27017为PRIMARYThu Aug  4 11:41:28.422 [rsHealthPoll] replSet member 127.0.0.1:27018 is upThu Aug  4 11:41:28.422 [rsHealthPoll] replSet member 127.0.0.1:27018 is now in state SECONDARY//27018为SECONDARY主库上日志Thu Aug  4 11:41:28.270 [rsHealthPoll] replset info 127.0.0.1:27019 thinks that we are downThu Aug  4 11:41:28.270 [rsHealthPoll] replSet member 127.0.0.1:27019 is upThu Aug  4 11:41:28.272 [rsHealthPoll] replSet member 127.0.0.1:27019 is now in state STARTUP2Thu Aug  4 11:41:30.273 [rsHealthPoll] replSet member 127.0.0.1:27019 is now in state ARBITER//27019已经正常
  6. 切换测试(停止主库)

    //关闭主节点服务器进程Thu Aug  4 11:49:05.375 [rsMgr] replSet info electSelf 2Thu Aug  4 11:49:05.564 [rsMgr] replSet PRIMARYThu Aug  4 11:49:07.287 [rsHealthPoll] replset info 127.0.0.1:27017 heartbeat failed, retryingThu Aug  4 11:49:09.291 [rsHealthPoll] replset info 127.0.0.1:27017 heartbeat failed, retrying//从库变主库zxq:SECONDARY> zxq:PRIMARY> zxq:PRIMARY> //从库变主库,可以接管业务zxq:SECONDARY> db.zxq.find()error: { "$err" : "not master and slaveOk=false", "code" : 13435 }zxq:PRIMARY> db.zxq.find()db.zxq.find(){ "_id" : ObjectId("57a2931b90d8e955cf551d2c"), "name" : "a", "age" : "10" }{ "_id" : ObjectId("57a293fe90d8e955cf551d2d"), "name" : "b", "age" : "11" }{ "_id" : ObjectId("57a2bd7106e8981bb7d168ea"), "name" : "c", "age" : "12" }

分片

mongodb采用将集合进行拆分,然后将拆分的数据均摊到几个片上的一种解决方案

  • mongos就是一个路由服务器,它会根据管理员设置的“片键”将数据分摊到自己管理的mongod集群

  • 数据和片的对应关系以及相应的配置信息保存在”config服务器”上

  • 所有的client请求我们都是由 mongos去转向的,本身不存留数据

  • mongod: 一个普通的数据库实例,如果不分片的话,我们会直接连上mongod。

    127.0.0.1:27017  作为 mongos服务器127.0.0.1:27018  作为 config 服务器127.0.0.1:28000  作为一个sharing1服务器127.0.0.1:28001  作为一个sharing2服务器

配置基本服务

  • 开启config服务器

    其实就是一个普通的mongod服务。/mongodb/config/mongod --port=27018 --dbpath=/mongodb/config/db
  • 开启mongos服务

    /mongodb/master/mongos --port=27017 configdb=127.0.0.1:27018 
  • 开启两个片键

    /mongodb/s1/mongod --port=28000 --dbpath=/mongodb/s1/db/mongodb/s2/mongod --port=28001 --dbpath=/mongodb/s2/db

初始化配置

  • 将要作为“片”的机器放到mongos的config配置中

    登录到mongos/mongodb/bin/mongo 127.0.0.1:27017connecting to: 127.0.0.1:27017/testmongos> use adminswitched to db adminmongos> db.runCommand({"addshard":"127.0.0.1:28000","allowLocal":true})    { "shardAdded" : "shard0000", "ok" : 1 }mongos> db.runCommand({"addshard":"127.0.0.1:28001","allowLocal":true})    { "shardAdded" : "shard0001", "ok" : 1 }
  • 准备分片文档

    一定要在分片之前创建 “片键” 的索引

    mongos> use testswitched to db testmongos>db.zxq.insert({"name":"jack","age":1})mongos> db.zxq.createIndex({"age":1})循环插入数据:for(var i=1;i<10000;i++){db.zxq.insert({"name":"jack"+i,"age":i})}
  • 激活并创建分片

    mongos> use adminswitched to db adminmongos> db.runCommand({"enablesharding":"test"})mongos> db.runCommand({"shardcollection":"test.zxq","key":{"age":1}}){ "collectionsharded" : "test.zxq", "ok" : 1 }
  • 查看分片

    db.shards.find()