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, ) - bulk execute write operations, optional parameters are: w, wtimeout, j db.mycoll.count( query = {}, ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS db.mycoll.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied. db.mycoll.convertToCapped(maxBytes) - calls {convertToCapped:'mycoll', size:maxBytes}} command db.mycoll.createIndex(keypattern[,options]) db.mycoll.createIndexes([keypatterns], ) db.mycoll.dataSize() db.mycoll.deleteOne( filter, ) - delete first matching document, optional parameters are: w, wtimeout, j db.mycoll.deleteMany( filter, ) - delete all matching documents, optional parameters are: w, wtimeout, j db.mycoll.distinct( key, query, ) - e.g. db.mycoll.distinct( 'x' ), optional parameters are: maxTimeMS db.mycoll.drop() drop the collection db.mycoll.dropIndex(index) - e.g. db.mycoll.dropIndex( "indexName" ) or db.mycoll.dropIndex( { "indexKey" : 1 } ) db.mycoll.dropIndexes() db.mycoll.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead db.mycoll.explain().help() - show explain help db.mycoll.reIndex() db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.mycoll.find( {x:77} , {name:1, x:1} ) db.mycoll.find(...).count() db.mycoll.find(...).limit(n) db.mycoll.find(...).skip(n) db.mycoll.find(...).sort(...) db.mycoll.findOne([query], [fields], [options], [readConcern]) db.mycoll.findOneAndDelete( filter, ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS db.mycoll.findOneAndReplace( filter, replacement, ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.mycoll.findOneAndUpdate( filter, update, ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.mycoll.getDB() get DB object associated with collection db.mycoll.getPlanCache() get query plan cache associated with collection db.mycoll.getIndexes() db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.mycoll.insert(obj) db.mycoll.insertOne( obj, ) - insert a document, optional parameters are: w, wtimeout, j db.mycoll.insertMany( [objects], ) - insert multiple documents, optional parameters are: w, wtimeout, j db.mycoll.mapReduce( mapFunction , reduceFunction , ) db.mycoll.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor db.mycoll.remove(query) db.mycoll.replaceOne( filter, replacement, ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j db.mycoll.renameCollection( newName , ) renames the collection. db.mycoll.runCommand( name , ) runs a db command with the given name where the first param is the collection name db.mycoll.save(obj) db.mycoll.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: }) db.mycoll.storageSize() - includes free space allocated to this collection db.mycoll.totalIndexSize() - size in bytes of all the indexes db.mycoll.totalSize() - storage allocated for all data and indexes db.mycoll.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi db.mycoll.updateOne( filter, update, ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j db.mycoll.updateMany( filter, update, ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j db.mycoll.validate( ) - SLOW db.mycoll.getShardVersion() - only for use with sharding db.mycoll.getShardDistribution() - prints statistics about data distribution in the cluster db.mycoll.getSplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function db.mycoll.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set db.mycoll.setWriteConcern( ) - sets the write concern for writes to the collection db.mycoll.unsetWriteConcern( ) - unsets the write concern for writes to the collection db.mycoll.latencyStats() - display operation latency histograms for this collection sh.help() sh.addShard( host ) server:port OR setname/server:port sh.addShardToZone(shard,zone) adds the shard to the zone sh.updateZoneKeyRange(fullName,min,max,zone) assigns the specified range of the given collection to a zone sh.disableBalancing(coll) disable balancing on one collection sh.enableBalancing(coll) re-enable balancing on one collection sh.enableSharding(dbname) enables sharding on the database dbname sh.getBalancerState() returns whether the balancer is enabled sh.isBalancerRunning() return true if the balancer has work in progress on any mongos sh.moveChunk(fullName,find,to) move the chunk where 'find' is to 'to' (name of shard) sh.removeShardFromZone(shard,zone) removes the shard from zone sh.removeRangeFromZone(fullName,min,max) removes the range of the given collection from any zone sh.shardCollection(fullName,key,unique,options) shards the collection sh.splitAt(fullName,middle) splits the chunk that middle is in at middle sh.splitFind(fullName,find) splits the chunk that find is in at the median sh.startBalancer() starts the balancer so chunks are balanced automatically sh.status() prints a general overview of the cluster sh.stopBalancer() stops the balancer so chunks are not balanced automatically sh.disableAutoSplit() disable autoSplit on one collection sh.enableAutoSplit() re-eable autoSplit on one colleciton sh.getShouldAutoSplit() returns whether autosplit is enabled

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的基本操作下篇再进行说明。

by peng.lee