新博客地址, 请多多支持

帮助命令查看

help                         show help

show dbs                     show database names

show collections             show collections in current database

show users                   show users in current database

show profile                 show most recent system.profile entries with time >= 1ms

use                 set curent database to

db.addUser (username, password)

db.removeUser(username)

db.cloneDatabase(fromhost)

db.copyDatabase(fromdb, todb, fromhost)

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

db.getName()

db.dropDatabase()

// runs the collstats] command on each collection in the database

db.printCollectionStats()

db.currentOp() displays the current operation in the db

db.killOp() kills the current operation in the db

db.getProfilingLevel()

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

db.getReplicationInfo()

db.printReplicationInfo()

db.printSlaveReplicationInfo()

db.repairDatabase()

db.version() current version of the server

db.commandHelp("collStats")

db.shutdownServer()


        #######################collections(集合帮帮助)###########################

 

db.foo.drop() drop the collection

db.foo.dropIndex(name)

db.foo.dropIndexes()

db.foo.getIndexes()

db.foo.ensureIndex(keypattern,options) - options object has these possible

                                         fields: name, unique, dropDups

db.foo.find( [query] , [fields])       - first parameter is an optional

                                         query filter. second parameter

                                         is optional

                                         set of fields to return.

                                            e.g. db.foo.find(

                                                  { x : 77 } ,

                                                  { name : 1 , x : 1 } )

db.foo.find(...).count()

db.foo.find(...).limit(n)

db.foo.find(...).skip(n)

db.foo.find(...).sort(...)

db.foo.findOne([query])

db.foo.getDB() get DB object associated with collection

db.foo.count()

db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )

db.foo.renameCollection( newName ) renames the collection

db.foo.stats()

db.foo.dataSize()

db.foo.storageSize() - includes free space allocated to this collection

db.foo.totalIndexSize() - size in bytes of all the indexes

db.foo.totalSize() - storage allocated for all data and indexes

db.foo.validate() (slow)

db.foo.insert(obj)

db.foo.update(query, object[, upsert_bool])

db.foo.save(obj)

db.foo.remove(query)                   - remove objects matching query

                                         remove({}) will remove all



     #######################  replset command###############

rs.help()

         rs.status()                     { replSetGetStatus : 1 } checks repl set status

         rs.initiate()                   { replSetInitiate : null } initiates set with default settings

         rs.initiate(cfg)                { replSetInitiate : cfg } initiates set with configuration cfg

         rs.conf()                       get the current configuration object from

local.system.replset

         rs.reconfig(cfg)                updates the configuration of a running replica set with

cfg (disconnects)

         rs.add(hostportstr)             add a new member to the set with default attributes

(disconnects)

         rs.add(membercfgobj)            add a new member to the set with extra attributes

(disconnects)

         rs.addArb(hostportstr)          add a new member which is arbiterOnly:true

(disconnects)

         rs.stepDown([secs])             step down as primary (momentarily) (disconnects)

         rs.freeze(secs)                 make a node ineligible to become primary for the time

specified

         rs.remove(hostportstr)          remove a host from the replica set (disconnects)

         rs.slaveOk()                    shorthand for db.getMongo().setSlaveOk()

 

         db.isMaster()                   check who is primary

                 

常用命令
     如果忘记了,可以用以下的命令查看:

help

db.help();

db.yourColl.help();

db.youColl.find().help();

rs.help(); 

1、  进入数据库:

       useadmin

2、  查看用户列表

db.system.users.find()

3、  增加用记或修改用户密码

   db.addUser(‘name’,’pwd’,true)        其中true是否是只读

4、  用户认证

   db.auth(‘name’,’pwd’,true)     其中true是否是只读,当显示为1时表示成功。

5、  删除用户

db.removeUser(‘name’)

6、  查看所有用户:

    show users

7、  查看所有数据库

show dbs

8、  查看所有的collection的状态

show collections

9、     查看各collection的状态

db.printCollectionsStats()

    10、查看主从复制状态

           db.printReplicationInfo()

    11、修复数据库

                       db.repairDatabase()

    12、设置记录profiling0=off 1=slow 2=all

                            db.setProfilingLevel(1)

    13查看profiling

                     showprofile

    14  拷贝数据库

                     db.copyDatabase('mail_addr','mail_addr_tmp')

    15  删除collection

                     db.mail_addr.drop()

    16删除当前的数据库

                     db.dropDatabase()

17、查看同步情况状态

       db.printReplicationInfo();

18、手动同步:

       use admin

       db.runCommand ( {"resync": 1 } )

19、关闭数据库

       db.shutdownServer()

    当出现:Error:couldn't connect to server 127.0.0.1 shell/mongo.js:84

      (1)rm/mongodb/data/mongo.lock

      (2)mongod--repair

      (3)、重启

20、从指定主机上克隆数据库

db.cloneDatabase(“127.0.0.1”);

    21、从指定的机器上复制指定数据库数据到某个数据库

          db.copyDatabase("mydb", "temp","127.0.0.1");

              将本机的mydb的数据复制到temp数据库中

    22、删除当前使用数据库

          db.dropDatabase();

23查看当前db的链接机器地址      db.getMongo();

                三、增加删除修改

1Insert

db.user.insert({'name':'dump','age':1})

or

db.user.save({'name':'dump','age':1})

         嵌套对象:         db.foo.save({'name':'dump','address':{'city':'hangzhou','post':310015},'phone':[13

           数组对象:

db.user_addr.save({'Uid':'dump','Al':['[email protected]','[email protected]']})

     2delete

          删除name=’dump’的用户信息:

                db.user.remove({'name':'dump'})

            删除foo表所有信息:

                db.foo.remove()

        3update

db.wkgbc.update({"id":10},{"$set":{"name":"Gavin","value1":110}})只更新第一条

db.wkgbc.update({"id":10},{"$set":{"name":"Gavin","value1":110}},false,true) 全部更新

db.wkgbc.update({"id":10},{"$set":{"name":"Gavin","value1":110}},true,true) 全部更新,且如果更新的字段不存在,则加入。

db.wkgbc.update({"id":11},{"$inc":{"value5":120}}) 其中inc是加入一个新的字段

db.wkgbc.update({"id":11},{"$unset":{"value5":110}})  删除字段

 

                  四、其它

查询:

coll.find() // select * from collcoll.find().limit(10) // select * from coll limit 10coll.find().sort({x:1}) // select * from coll order by x asc 升序 -1降序coll.find().sort({x:1}).skip(5).limit(10) // select * from coll order by x asc limit 5, 10coll.find({x:10}) // select * from coll where x = 10coll.find({x: {$lt:10}}) // select * from coll where x coll.find({}, {y:true}) // select y from collcoll.count() //select count(*) from colldb.wkgbc.find({id:{$mod:[10,1]}})   查询1-10外的数,(其中1会显示出来)   db.wkgbc.find({id:{$ne:3}})     3外,显示所有数据db.wkgbc.find({id:{$in:[3]}})      显示等于3的数据db.wkgbc.find( { $and: [ { id: 10 }, { id : { $gt: 5 } } ] } ) 显示id大于5id等于10db.wkgbc.find({"UserName":/keyword/})  查看关键字db.wkgbc.find({"UserName":/^keyword/})  查看开头关键字db.wkgbc.find({"UserName":/keyword$/})   查看结尾关键字db.wkgbc.find().count()                 统计条数db.wkgbc.find({"$or":[{"id":10},{"value1":/00/}]},{"id":true}) 查找id=0的或value100的关键字的数据,其中id:true是只显示这两个字段,去掉会显示所有字段的数据

 

其他:

wkgbc.find({"address.city":"gz"}) // 搜索嵌套文档addresscity值为gz的记录

wkgbc.find({likes:"math"}) // 搜索数组

wkgbc.find({name: {$exists: true}}); //查询所有存在name字段的记录

wkgbc.find({phone: {$exists: false}}); //查询所有不存在phone字段的记录

wkgbc.find({name: {$type: 2}}); //查询所有name字段是字符类型的wkgbc.find({age:{$type:

索引:

wkgbc.ensureIndex({productid:1}) // productid上建立普通索引wkgbc.ensureIndex({district:1, plate:1}) // 多字段索引wkgbc.ensureIndex({"address.city":1}) // 在嵌套文档的字段上建索引wkgbc.ensureIndex({productid:1}, {unique:true}) // 唯一索引wkgbc.ensureIndex({productid:1}, {unique:true, dropDups:true|) // 建索引时,如果遇到索引字段值已经出现过的情况,则删除重复记录wkgbc.getIndexes() // 查看索引wkgbc.dropIndex({productid:1}) // 删除单个索引

Mongostat性能健康查看
db.stats()

PRIMARY> db.stats()

{

         "db" : "admin",         当前数据库

         "wkgbcections" : 0,        集合数量

         "objects" : 0,          

         "avgObjSize" : 0,         平均obj大小

         "dataSize" : 0,           数据库总大小

         "storageSize" : 0,         储存大小

         "numExtents" : 0,      

         "indexes" : 0,          索引数

         "indexSize" : 0,         索引大小

         "fileSize" : 0,           文件大小

         "nsSizeMB" : 0,        

         "ok" : 1

}


db.serverStatus()

PRIMARY> db.serverStatus()

{

         "host" : "localhost.localdomain",

         "version" : "2.0.6",

         "process" : "mongod",

         "uptime" : 8345,

         "uptimeEstimate" : 7979,

         "localTime" : ISODate("2012-08-08T14:46:51.890Z"),

         "globalLock" : {

                   "totalTime" : 8345309312,

                   "lockTime" : 36546168,

                   "ratio" : 0.004379246668239012,

                   "currentQueue" : {       当前查询队列

                            "total" : 0,

                            "readers" : 0,

                            "writers" : 0

                   },

                   "activeClients" : {         客户端活动情况

                            "total" : 2,

                            "readers" : 2,

                            "writers" : 0

                   }

         },

         "mem" : {                   内存情况

                   "bits" : 64,              系统是64

                   "resident" : 177,

                   "virtual" : 3514,    journaling开启时,该值是mapped2倍。如果比mapped小,说明出现内在溢出

                   "supported" : true,

                   "mapped" : 1600,

                   "mappedWithJournal" : 3200

         },

         "connections" : {             连接数

                   "current" : 6,

                   "available" : 813         还有可用

         },

         "extra_info" : {           显示 一此额外系统信息

                   "note" : "fields vary by platform",

                   "heap_usage_bytes" : 717504,

                   "page_faults" : 2042

         },

         "indexCounters" : {          索引情况

                   "btree" : {

                            "accesses" : 3,

                            "hits" : 3,  

                            "misses" : 0,

                            "resets" : 0,    自数据库重启到今,索引重置了 几次

                            "missRatio" : 0    missesaccesses的比率,命中率

                   }

         },

         "backgroundFlushing" : {       写入磁盘情况

                   "flushes" : 139,

                   "total_ms" : 1872,

                   "average_ms" : 13.467625899280575,

                   "last_ms" : 1,

                   "last_finished" : ISODate("2012-08-08T14:46:46.836Z")

         },

         "cursors" : {            cursor使用信息和情况

                   "totalOpen" : 2,

                   "clientCursors_size" : 2,

                   "timedOut" : 0

         },

         "network" : {            网络流量

                   "bytesIn" : 39906966,

                   "bytesOut" : 78657624,

                   "numRequests" : 13333

         },

         "repl" : {               副本集群情况

                   "setName" : "myset",

                   "ismaster" : true,

                   "secondary" : false,

                   "hosts" : [           主机

                            "192.168.29.130:27017",

                            "192.168.29.128:27017",

                            "192.168.29.129:27017"

                   ],

                   "primary" : "192.168.29.130:27017",

                   "me" : "192.168.29.130:27017"

         },

         "opcounters" : {          操作情况

                   "insert" : 155,

                   "query" : 9,

                   "update" : 0,

                   "delete" : 0,

                   "getmore" : 4777,

                   "command" : 8397

         },

         "asserts" : {         报出来的错误信息    

                   "regular" : 0,

                   "warning" : 0,

                   "msg" : 0,

                   "user" : 0,

                   "rollovers" : 0

         },

         "writeBacksQueued" : false,       MongoDB写入磁盘情况

         "dur" : {             Journaling信息

                   "commits" : 29,    在上一次时间间隔

                   "journaledMB" : 0,     journale的大小

                   "writeToDataFilesMB" : 0,

                   "compression" : 0,

                   "commitsInWriteLock" : 0,

                   "earlyCommits" : 0,

                   "timeMs" : {          实例操作性能的时间

                            "dt" : 3103,

                            "prepLogBuffer" : 0,

                            "writeToJournal" : 0,

                            "writeToDataFiles" : 0,

                            "remapPrivateView" : 0

                   }

         },

         "ok" : 1

}


db.currentOp()

   在一台有负载的机器上:currentOp()

MongoDB 常用命令及性能查看-LMLPHP

在一台没有负载的机器上:

MongoDB 常用命令及性能查看-LMLPHP

如果发现一个操作太长,把数据库卡死的话,可以用这个命令杀死他

>db.killOp("shard3:466404288")

rs.status()

SECONDARY> rs.status();

{

         "set" : "myset",          replset的名字

         "date" : ISODate("2012-08-08T06:13:35Z"),      

         "myState" : 2,

         "syncingTo" : "192.168.101.132:27017",

         "members" : [

                   {

                            "_id" : 3,              成员号

                            "name" : "192.168.101.131:27017",

                            "health" : 1,          其中0表示服务down1表示良好

                            "state" : 2,           

                            "stateStr" : "SECONDARY",     表示是primary还是secondary

                            "optime" : {

                                     "t" : 1344406326000,

                                     "i" : 2

                            },

                            "optimeDate" : ISODate("2012-08-08T06:12:06Z"),

                            "self" : true

                   },

                  {

                            "_id" : 4,

                            "name" : "192.168.201.131:27017",

                            "health" : 0,

                            "state" : 8,

                            "stateStr" : "(not reachable/healthy)",

                            "uptime" : 0,

                            "optime" : {

                                     "t" : 1344364497000,

                                     "i" : 4

                            },

                            "optimeDate" : ISODate("2012-08-07T18:34:57Z"),

                            "lastHeartbeat" : ISODate("2012-08-07T18:52:47Z"),

                            "pingMs" : 0,     表示这个节点到另一个节点发出的心跳命令时长

                            "errmsg" : "socket exception"

                   },

其中state的解释:

0

Starting up, phase 1 (parsing configuration)

1

Primary

2

Secondary

3

Recovering (initial syncing, post-rollback, stale members)

4

Fatal error

5

Starting up, phase 2 (forking threads)

6

Unknown state (member has never been reached)

7

Arbiter

8

Down

9

Rollback

10

Removed

mongostat详解

mongostatmongdb自带的状态检测工具,在命令行下使用。它会间隔固定时间获取mongodb的当前运行状态,并输出。如果你发现数据库突然变慢或者有其他问题的话,你第一手的操作就考虑采用mongostat来查看mongo的状态。

它的输出有以下几列:

·         inserts/s 每秒插入次数

·         query/s 每秒查询次数

·         update/s 每秒更新次数

·         delete/s 每秒删除次数

·         getmore/s 每秒执行getmore次数

·         command/s 每秒的命令数,比以上插入、查找、更新、删除的综合还多,还统计了别的命令

·         flushs/s 每秒执行fsync将数据写入硬盘的次数。

·         mapped/s 所有的被mmap的数据量,单位是MB

·         vsize 虚拟内存使用量,单位MB

·         res 物理内存使用量,单位MB

·         faults/s 每秒访问失败数(只有Linux有),数据被交换出物理内存,放到swap。不要超过100,否则就是机器内存太小,造成频繁swap写入。此时要升级内存或者扩展

·         locked % 被锁的时间百分比,尽量控制在50%以下吧

·         idx miss % 索引不命中所占百分比。如果太高的话就要考虑索引是不是少了

·         q t|r|w Mongodb接收到太多的命令而数据库被锁住无法执行完成,它会将命令加入队列。这一栏显示了总共、读、写3个队列的长度,都为0的话表示mongo毫无压力。高并发时,一般队列值会升高。

·         conn 当前连接数

·         time 时间戳

2、使用profiler

    Profiler默认是关闭的, MongoDB可以监控所有慢的以及不慢的查询。

慢查询的时候开启。

use test

switched to db test

> db.setProfilingLevel(2); 设定级别

{"was" : 0 , "slowms" : 100, "ok" : 1} // "was" is the old setting

> db.getProfilingLevel()   查看级别

2

查看Profile日志:

> db.system.profile.find().sort({$natural:-1})

{"ts" : "Thu Jan 29 2009 15:19:32 GMT-0500 (EST)" , "info" :

"query test.$cmd ntoreturn:1 reslen:66 nscanned:0 query: { profile: 2 } nreturned:1 bytes:50" ,

"millis" : 0} ...

·         字段意思

·         ts:时间戳

·         info:具体的操作

·         millis:操作所花时间,毫秒

 官网解释:http://www.mongodb.org/display/DOCS/Database+Profiler

使用Web控制台

的端口在Mongodb数据库服务器端口的基础上加1000,如果是默认的Mongodb数据服务端口(Which is 27017),则相应的Web端口为28017

这个页面可以看到

·         当前Mongodb的所有连接

·         各个数据库和Wkgbcection的访问统计,包括:Reads, Writes,Queries, GetMores ,Inserts, Updates, Removes

·         写锁的状态

·         以及日志文件的最后几百行(CentOS+10gen yum 安装的mongodb默认的日志文件位于/var/log/mongo/mongod.log)

l  其中web查看的数据相当于rs.status()显示的数据。
10-28 21:08