mongoDB笔记

  • 创建一个超级用户
gulu@Dell:/www/wdlinux/mongodb/bin$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use admin
switched to db admin
> db.addUser("root", "123456")
{
    "_id" : ObjectId("579ea9507bc4a3ce560c4e05"),
    "user" : "root",
    "readOnly" : false,
    "pwd" : "b3098ef4591719e9f75972a75883726b"
}

一条命令不用打分号哦,mysql要加!只需要输入db.addUser(“root”, “123456”),后面的是自动提示!

db.addUser是老版本的操作,现在版本也还能继续使用,创建出来的user是带有root role的超级管理员。

  • 用户登录
mongo -u root -p 123456 --authenticationDatabase admin
  • 查询用户find
> use admin
> db.system.users.find()
{ "_id" : ObjectId("579ea9507bc4a3ce560c4e05"), "user" : "root", "readOnly" : false, "pwd" : "b3098ef4591719e9f75972a75883726b" }

help查看支持命令

    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    sh.help()                    sharding helpers
    rs.help()                    replica set helpers
    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

db支持哪些方法

> db.help(); 
DB methods:
    db.addUser(userDocument)
    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
    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 currently executing operations in the db
    db.dropDatabase()
    db.eval(func, args) run code server-side
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    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 queries on a replication slave server
    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.hostInfo() get details about the server's host
    db.isMaster() check replica primary status
    db.killOp(opid) kills the current operation in the db
    db.listCommands() lists all the db commands
    db.loadServerScripts() loads all the scripts in db.system.js
    db.logout()
    db.printCollectionStats()
    db.printReplicationInfo()
    db.printShardingStatus()
    db.printSlaveReplicationInfo()
    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.setVerboseShell(flag) display extra information in shell output
    db.shutdownServer()
    db.stats()
    db.version() current version of the server

具体数据库操作

> db.guess.help()
DBCollection help
    db.guess.find().help() - show DBCursor help
    db.guess.count()
    db.guess.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.guess.convertToCapped(maxBytes) - calls {convertToCapped:'guess', size:maxBytes}} command
    db.guess.dataSize()
    db.guess.distinct( key ) - e.g. db.guess.distinct( 'x' )
    db.guess.drop() drop the collection
    db.guess.dropIndex(index) - e.g. db.guess.dropIndex( "indexName" ) or db.guess.dropIndex( { "indexKey" : 1 } )
    db.guess.dropIndexes()
    db.guess.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
    db.guess.reIndex()
    db.guess.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                  e.g. db.guess.find( {x:77} , {name:1, x:1} )
    db.guess.find(...).count()
    db.guess.find(...).limit(n)
    db.guess.find(...).skip(n)
    db.guess.find(...).sort(...)
    db.guess.findOne([query])
    db.guess.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
    db.guess.getDB() get DB object associated with collection
    db.guess.getIndexes()
    db.guess.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
    db.guess.insert(obj)
    db.guess.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.guess.remove(query)
    db.guess.renameCollection( newName , <dropTarget> ) renames the collection.
    db.guess.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
    db.guess.save(obj)
    db.guess.stats()
    db.guess.storageSize() - includes free space allocated to this collection
    db.guess.totalIndexSize() - size in bytes of all the indexes
    db.guess.totalSize() - storage allocated for all data and indexes
    db.guess.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
    db.guess.validate( <full> ) - SLOW
    db.guess.getShardVersion() - only for use with sharding
    db.guess.getShardDistribution() - prints statistics about data distribution in the cluster
    db.guess.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function

  • 显示所有数据库
> show dbs
admin   0.203125GB
guess   0.203125GB
lbs_people  0.203125GB
local   0.078125GB
mongodb 0.203125GB
statues 0.203125GB
test    (empty)
  • 显示当前所进入的数据库
> db
guess
  • 显示当前选择的db中的集合
> show collections; 
  • 删除某个数据库people
> use people
switched to db people
> db.dropDatabase()
{ "dropped" : "people", "ok" : 1 }
> db
people
> show dbs
admin   0.203125GB
local   0.078125GB
mongodb 0.203125GB
statues 0.203125GB
test    (empty)
> 

建立表:
db.createCollection(‘settings’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值