mongodb學習(-)

MongoDB 是一個基於分佈式文件存儲的數據庫。由 C++ 語言編寫。
旨在爲 WEB 應用提供可擴展的高性能數據存儲解決方案。
MongoDB 是一個介於關係數據庫和非關係數據庫之間的產品,是非關係數據庫當中功能最豐富,最像關係數據庫的。

什麼是NoSQL?
NoSQL,指的是非關係型的數據庫。NoSQL有時也稱作Not Only SQL的縮寫,
是對不同於傳統的關係型數據庫的數據庫管理系統的統稱。
NoSQL用於超大規模數據的存儲。(例如谷歌或Facebook每天爲他們的用戶收集萬億比特的數據)。
這些類型的數據存儲不需要固定的模式,無需多餘操作就可以橫向擴展。


mongodb複製集配置
因爲機器比較卡,所以就搭建在一臺虛擬機裏了,配置複製集,至少需要3個實例
master    192.168.1.156:27017
slave    192.168.1.156:37017
arbiter    192.168.1.156:47017



[root@Warfare_all_192.168.1.156 ~]# egrep -v '^#|^$' /etc/mongodb.conf 
bind_ip = 192.168.1.156
port = 27017
fork = true
pidfilepath = /var/run/mongodb/mongodb.pid
logpath = /var/log/mongodb/mongodb.log
dbpath =/var/lib/mongodb
journal = true
replSet = shard1
nohttpinterface = true

[root@Warfare_all_192.168.1.156 ~]# egrep -v '^#|^$' /etc/mongodb_37017.conf 
bind_ip = 192.168.1.156
port = 37017
fork = true
pidfilepath = /var/run/mongodb_37017/mongodb.pid
logpath = /var/log/mongodb_37017/mongodb.log
dbpath =/var/lib/mongodb_37017
journal = true
replSet = shard1
nohttpinterface = true

[root@Warfare_all_192.168.1.156 ~]# egrep -v '^#|^$' /etc/mongodb_47017.conf 
bind_ip = 192.168.1.156
port = 47017
fork = true
pidfilepath = /var/run/mongodb_47017/mongodb.pid
logpath = /var/log/mongodb_47017/mongodb.log
dbpath =/var/lib/mongodb_47017
journal = true
replSet = shard1
nohttpinterface = true


ps aux |grep mongo
root      62095  0.6  3.1 3304700 60460 ?       Sl   20:07   0:24 mongod --quiet -f /etc/mongodb_57017.conf
root      62387  0.6  2.0 2944248 39176 ?       Sl   20:08   0:24 mongod --quiet -f /etc/mongodb_47017.conf
root      66145  0.6  3.5 5419352 67156 ?       Sl   20:20   0:18 mongod --quiet -f /etc/mongodb_37017.conf
root      68910  0.6  3.1 5264784 60024 ?       Sl   20:25   0:16 mongod --quiet -f /etc/mongodb.conf
[root@Warfare_all_192.168.1.156 ~]# mongo --host=192.168.1.156
MongoDB shell version: 2.4.14
connecting to: 192.168.1.156:27017/test
shard1:PRIMARY> show dbs;
local2.0771484375GB
test0.203125GB
wabao0.203125GB
shard1:PRIMARY>rs.conf()
{
	"_id" : "shard1",
	"version" : 15,
	"members" : [
		{
			"_id" : 0,
			"host" : "192.168.1.156:27017",
			"priority" : 10
		},
		{
			"_id" : 1,
			"host" : "192.168.1.156:37017",
			"priority" : 5
		},
		{
			"_id" : 2,
			"host" : "192.168.1.156:57017",
			"priority" : 3
		}
	]
}
 
shard1:PRIMARY>rs.conf() 



shard1:PRIMARY> 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
shard1:PRIMARY> 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
shard1:PRIMARY> 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.syncFrom(hostportstr)        make a secondary to sync from the given member
	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
	db.printReplicationInfo()       check oplog size and time range

	reconfiguration helpers disconnect from the database so the shell will display
	an error, even if the command succeeds.
	see also http://<mongod_host>:28017/_replSet for additional diagnostic info
shard1:PRIMARY> db.collection.find().help()
find() modifiers
	.sort( {...} )
	.limit( n )
	.skip( n )
	.count() - total # of objects matching query, ignores skip,limit
	.size() - total # of objects cursor would return, honors skip,limit
	.explain([verbose])
	.hint(...)
	.addOption(n) - adds op_query options -- see wire protocol
	._addSpecial(name, value) - http://dochub.mongodb.org/core/advancedqueries#AdvancedQueries-Metaqueryoperators
	.batchSize(n) - sets the number of docs to return per getMore
	.showDiskLoc() - adds a $diskLoc field to each returned object
	.min(idxDoc)
	.max(idxDoc)

Cursor methods
	.toArray() - iterates through docs and returns an array of the results
	.forEach( func )
	.map( func )
	.hasNext()
	.next()
	.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
	.count(applySkipLimit) - runs command at server
	.itcount() - iterates through documents and counts them
shard1:PRIMARY> sh.help()
	sh.addShard( host )                       server:port OR setname/server:port
	sh.enableSharding(dbname)                 enables sharding on the database dbname
	sh.shardCollection(fullName,key,unique)   shards the collection
	sh.splitFind(fullName,find)               splits the chunk that find is in at the median
	sh.splitAt(fullName,middle)               splits the chunk that middle is in at middle
	sh.moveChunk(fullName,find,to)            move the chunk where 'find' is to 'to' (name of shard)
	sh.setBalancerState( <bool on or not> )   turns the balancer on or off true=on, false=off
	sh.getBalancerState()                     return true if enabled
	sh.isBalancerRunning()                    return true if the balancer has work in progress on any mongos
	sh.addShardTag(shard,tag)                 adds the tag to the shard
	sh.removeShardTag(shard,tag)              removes the tag from the shard
	sh.addTagRange(fullName,min,max,tag)      tags the specified range of the given collection
	sh.status()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章