MongoDB是由c++编写,是一个基于分布式文件存储的开源数据库系统。数据结构由键值对组成,类似于json对象。
Mongodb支持Red Hat、SUSE、Amazon、Ubuntu、Debian系统的安装包直接安装。公司自己的操作系统不在这个范围内,所以需要通过Tarball安装。Tarball安装支持除了前面列举的 linux系统之外的安装。注意,如果是前面列举的操作系统之一,就不要再采用这种方式安装了。
安装MongoDB 社区版本
MondgoDB目前只提供64位linux系统。按照下面的安装步骤进行安装。我选择的是3.2版本
- 下载MongoDB二进制文件
例如:
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.2.tgz
至于下载到哪个目录,根据自己情况自定义选择。
-
解压tgz包
tar xf mongodb-linux-x86_64-3.4.2.tgz
-
复制解压包内容到指定目录
cp mongodb-linux-x86_64-3.4.2/* . -rf # 我复制到当前目录
-
添加mongodb的二进制目录到PATH变量
export PATH=
/bin:$PATH
mongodb-install-directory 替换为实际存放目录
运行社区版MongoDB
在启动MongoDB之前,创建一个用于mongod程序写入数据的目录。默认情况下,mongod程序使用/data/db目录。 如果想创建其他目录,并使用,需要在启动mongod前通过dbpath指定。
-
创建数据库存放的位置和日志文件
mkdir -p /data/db
-
设置data目录的权限 运行mongod之前,需要确保mongod可以具有读写目录的权限。
-
运MongoDB
不指定路径启动 如果系统环境变量PATH包括mongod,并且使用默认的数据仓库(/data/db),可以通过mongod简单的启动:
mongod
启动log片段:
2016-12-01T10:56:56.238+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2016-12-01T10:56:56.504+0800 I INDEX [initandlisten] build index on: admin.system.version properties: { v: 2, key: { version: 1 }, name: "incompatible_with_version_32", ns: "admin.system.version" }
2016-12-01T10:56:56.504+0800 I INDEX [initandlisten] building index using bulk method; build may temporarily use up to 500 megabytes of RAM
2016-12-01T10:56:56.504+0800 I INDEX [initandlisten] build index done. scanned 0 total records. 0 secs
2016-12-01T10:56:56.505+0800 I COMMAND [initandlisten] setting featureCompatibilityVersion to 3.4
2016-12-01T10:56:56.505+0800 I NETWORK [thread1] waiting for connections on port 27017
指定mongod路径启动 使用mongod的绝对路径,启动
<path to binary>/mongod
指定数据仓库路径
mongod --dbpath <path to data directory>
mongod 参数查询 mongod -h
MongoDB使用
为了帮助使用MongoDB, MongoDB提供了各种驱动程序版本的入门指南 在生产环境中部署MongoDB之前,请参考Production Notes文档。 要停止MongoDB,请在运行mongod实例的终端中按Control+C
通过mongo连接数据库
mongo
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
查询所有的数据库
show databases
查询结果
admin 0.000GB 不可用
local 0.000GB 不可用
常用方法:
> 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 methods:
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.createView(name, viewOn, [ { $operator: {...}}, ... ], { viewOptions } )
db.createUser(userDocument)
db.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval() - deprecated
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.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
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.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
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.dropUser(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.setLogLevel(level,<component>)
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
指定数据库的集合进行操作、管理和监控
DBCollection help
db.mycoll.find().help() - show DBCursor help
db.mycoll.bulkWrite( operations,
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([stepdownSecs, catchUpSecs]) step down as primary (disconnects) rs.syncFrom(hostportstr) make a secondary 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() allow queries on secondary nodes
rs.printReplicationInfo() check oplog size and time range
rs.printSlaveReplicationInfo() check replica set members and replication lag
db.isMaster() check who is primary
reconfiguration helpers disconnect from the database so the shell will display
an error, even if the command succeeds.
mongodb的基本操作下篇再进行说明。