1、MongoDb 命令查询所有数据库列表
CODE:
> show dbs
2、查看当前连接在哪个数据库下面,可以直接输入db
CODE:
> db
Admin
3、切换到test数据库下面
CODE:
> use test
switched to db test
> db
Test
4、查看test下有哪些表或者叫collection
CODE:
> show collections
system.indexes
user
5、查看mongodb支持哪些命令,可以直接输入help
CODE:
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
rs.help() help on replica set methods
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
6、查看当前数据库支持哪些方法:
CODE:
> db.help();
DB methods:
db.addUser(username, password[, readOnly=false])
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.currentOp() displays the current operation in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()
db.removeUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.shutdownServer()
db.stats()
db.version() current version of the server
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnock() unlocks server following a db.fsyncLock()
7、根据条件查找数据
———————–
通过条件查询: 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.getIndexes() 显示表的所有索引
db.foo.group( { key : …, initial: …, reduce : …[, cond: …] } ) 根据条件分组
db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
db.foo.remove(query) 根据条件删除数据
db.foo.renameCollection( newName ) renames the collection 重命名表
db.foo.save(obj) 保存数据
db.foo.stats() 查看表的状态
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.update(query, object[, upsert_bool]) 根据条件更新数据
db.foo.validate() – SLOW 验证表的详细信息
db.foo.getShardVersion() – only for use with sharding
8、Mongodb的备份工具mongodump
如果想备份数据库test 如:
CODE:
lijj@wx2 ~ $ mongodump --help
Export MongoDB data to BSON files.
options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times for more
verbosity e.g. -vvvvv)
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for
sets)
--port arg server port. Can also use --host hostname:port
--ipv6 enable IPv6 support (disabled by default)
-u [ --username ] arg username
-p [ --password ] arg password
--dbpath arg directly access mongod database files in the given
path, instead of connecting to a mongod server -
needs to lock the data directory, so cannot be used
if a mongod is currently accessing the same path
--directoryperdb if dbpath specified, each db is in a separate
directory
--journal enable journaling
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
-o [ --out ] arg (=dump) output directory or "-" for stdout
-q [ --query ] arg json query
--oplog Use oplog for point-in-time snapshotting
--repair try to recover a crashed database
--forceTableScan force a table scan (do not use $snapshot)
lijj@wx2 ~ $ mongodump -d test -o ~/public_html/mongoDB/
connected to: 127.0.0.1
DATABASE: test to /home/lijj/public_html/mongoDB/test
test.system.users to /home/lijj/public_html/mongoDB/test/system.users.bson
2 objects
test.system.indexes to /home/lijj/public_html/mongoDB/test/system.indexes.bson
5 objects
test.test to /home/lijj/public_html/mongoDB/test/test.bson
3 objects
test.blog to /home/lijj/public_html/mongoDB/test/blog.bson
0 objects
test.foo to /home/lijj/public_html/mongoDB/test/foo.bson
1 objects
test.user to /home/lijj/public_html/mongoDB/test/user.bson
2 objects
lijj@wx2 mongoDB $ ls
test
9、MongoDB的数据恢复工具mongorestore
查看test库中的表
CODE:
> show collections
system.indexes
User
删除user表
CODE:
> db.user.drop();
True
> show collections
System.indexes
10、利用mongorestore 恢复刚才mongodump备份的数据
CODE:
lijj@wx2 ~ $ mongorestore --help
usage: mongorestore [options] [directory or filename to restore from]
options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times for more
verbosity e.g. -vvvvv)
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets)
--port arg server port. Can also use --host hostname:port
--ipv6 enable IPv6 support (disabled by default)
-u [ --username ] arg username
-p [ --password ] arg password
--dbpath arg directly access mongod database files in the given
path, instead of connecting to a mongod server -
needs to lock the data directory, so cannot be used
if a mongod is currently accessing the same path
--directoryperdb if dbpath specified, each db is in a separate
directory
--journal enable journaling
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
--objcheck validate object before inserting
--filter arg filter to apply before inserting
--drop drop each collection before import
--oplogReplay replay oplog for point-in-time restore
--keepIndexVersion don't upgrade indexes to newest version
lijj@wx2 ~ $ mongorestore -d test -c user ~/public_html/mongoDB/test/test.bson
connected to: 127.0.0.1
Wed Aug 1 15:23:53 /home/lijj/public_html/mongoDB/test/test.bson
Wed Aug 1 15:23:53 going into namespace [test.user]
3 objects found
test表中的3条记录已经恢复
CODE:
> show collections
blog
foo
system.indexes
system.users
test
user
> db.test.find()
{ “_id” : 1, “fruit” : [ “apple”, “banana”, “peach” ] }
{ “_id” : 2, “fruit” : [ “apple”, “kumquat”, “orange” ] }
{ “_id” : 3, “fruit” : [ “cherry”, “banana”, “apple” ] }
11、超级用户相关:
#增加或修改用户密码
db.addUser(‘admin’,’pwd’)
#查看用户列表
db.system.users.find()
#用户认证
db.auth(‘admin’,’pwd’)
#删除用户
db.removeUser(‘mongodb’)
#查看所有用户
show users
#查看所有数据库
show dbs
#查看所有的collection
show collections
#查看各collection的状态
db.printCollectionStats()
#查看主从复制状态
db.printReplicationInfo()
#修复数据库
db.repairDatabase()
#设置记录profiling,0=off 1=slow 2=all
db.setProfilingLevel(1)
#查看profiling
show profile
#拷贝数据库
db.copyDatabase(‘mail_addr’,’mail_addr_tmp’)
#删除collection
db.mail_addr.drop()
#删除当前的数据库
db.dropDatabase()
12、客户端连接
/usr/local/mongodb/bin/mongo user_addr -u user -p ‘pwd’
13、增删改
#存储嵌套的对象
db.foo.save({‘name’:’ysz’,’address’:{‘city’:’beijing’,’post’:100096},’phone’:[138,139]})
#存储数组对象
db.user_addr.save({‘Uid’:’lijj@sohu.com’,’Al’:[‘test-1@sohu.com’,’test-2@sohu.com’]})
#根据query条件修改,如果不存在则插入,允许修改多条记录
db.foo.update({‘yy’:5},{‘$set’:{‘xx’:2}},upsert=true,multi=true)
#删除yy=5的记录
db.foo.remove({‘yy’:5})
#删除所有的记录
db.foo.remove()
14、索引
增加索引:1(ascending),-1(descending)
db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
#索引子对象
db.user_addr.ensureIndex({‘Al.Em’: 1})
#查看索引信息
db.deliver_status.getIndexes()
db.deliver_status.getIndexKeys()
#根据索引名删除索引
db.user_addr.dropIndex(‘Al.Em_1’)
15、查询
查找所有
db.foo.find()
#查找一条记录
db.foo.findOne()
#根据条件检索10条记录
db.foo.find({‘msg’:’Hello 1′}).limit(10)
#sort排序
db.deliver_status.find({‘From’:’lijj@sohu.com’}).sort({‘Dt’,-1})
db.deliver_status.find().sort({‘Ct’:-1}).limit(1)
#count操作
db.user_addr.count()
#distinct操作
db.foo.distinct(‘msg’)
#>操作
db.foo.find({“timestamp”: {“$gte” : 2}})
#子对象的查找
db.foo.find({‘address.city’:’beijing’})
16、管理
查看collection数据的大小
db.deliver_status.dataSize()
#查看colleciont状态
db.deliver_status.stats()
#查询所有索引的大小
db.deliver_status.totalIndexSize()