常用
show dbs; #查看全部数据库show collections; #显示当前数据库中的集合(类似关系数据库中的表)show users; #查看当前数据库的用户信息use <db name>; #切换数据库跟mysql一样db;或者db.getName(); #查看当前所在数据库db.help(); #显示数据库操作命令,里面有很多的命令 db.foo.help(); #显示集合操作命令,同样有很多的命令,foo指的是当前数据库下,一个叫foo的集合,并非真正意义上的命令 db.foo.find(); #对于当前数据库中的foo集合进行数据查找(由于没有条件,会列出所有数据) db.foo.find( { a : 1 } ); #对于当前数据库中的foo集合进行查找,条件是数据中有一个属性叫a,且a的值为1
创库&用户
# 创建数据表db.createCollection("Account")db.createCollection("Test",{capped:true, size:10000}) { "ok" : 1 }capped:true,表示该集合的结构不能被修改;size:在建表之初就指定一定的空间大小,接下来的插入操作会不断地按顺序APPEND数据在这个预分配好空间的文件中,如果已经超出空间大小,则回到文件头覆盖原来的数据继续插入。这种结构保证了插入和查询的高效性,它不允许删除单个记录,更新的也有限制:不能超过原有记录的大小。这种表效率很高,它适用于一些暂时保存数据的场合,比如网站中登录用户的session信息,又比如一些程序的监控日志,都是属于过了一定的时间就可以被覆盖的数据。# 修改数据表名db.Account.renameCollection("Account1")# 创建用户db.createUser({user:"xiaoming",pwd:"123456",roles:[{role:"userAdmin",db:"test"}]})
Db.helper手册
> db.Account.help()DBCollection help db.Account.find().help() - show DBCursor help db.Account.count() db.Account.dataSize() db.Account.distinct( key ) - eg. db.Account.distinct( 'x' ) db.Account.drop() drop the collection db.Account.dropIndex(name) db.Account.dropIndexes() db.Account.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups db.Account.reIndex() db.Account.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.Account.find( {x:77} , {name:1, x:1} ) db.Account.find(...).count() db.Account.find(...).limit(n) db.Account.find(...).skip(n) db.Account.find(...).sort(...) db.Account.findOne([query]) db.Account.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) db.Account.getDB() get DB object associated with collection db.Account.getIndexes() db.Account.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.Account.mapReduce( mapFunction , reduceFunction , <optional params> ) db.Account.remove(query) db.Account.renameCollection( newName , <dropTarget> ) renames the collection. db.Account.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name db.Account.save(obj) db.Account.stats() db.Account.storageSize() - includes free space allocated to this collection db.Account.totalIndexSize() - size in bytes of all the indexes db.Account.totalSize() - storage allocated for all data and indexes db.Account.update(query, object[, upsert_bool, multi_bool]) db.Account.validate() - SLOW db.Account.getShardVersion() - only for use with sharding
资料