Toggle navigation
主页
工具
归档
标签
MongoDB
0
无
2020-09-02 12:01:50
0
0
myron
MongoDB db.createUser({user:"sysadmin",pwd:"sysadmin",roles:[{"role":"userAdminAnyDatabase","db":"admin"}]}) ## bi_test 库授权 use admin db.createUser({user:"admin",pwd:"123456",roles:["dbAdmin","readWrite"]}) db.auth('admin', '123456') db.grantRolesToUser ("admin",[{role: "read", db: "bi_test"},{role: "read", db: "admin"},{role: "read", db: "local"}] ) _____________________________________________________________________________________________ #!/bin/bash mongosync -h 192.168.0.12:19527 --to 192.168.0.168:27017 --oplog --logpath 12.lo g --logappend & 阿里云自建node1 : mongo eip.17k:27017 -u root -p ChineseAll -authenticationDatabase admin mongo 123.56.7.183:27017 -authenticationDatabase admin -u root -p ChineseAll 天津机房生产环境12: 2.4.5 mongo 125.39.195.12:19527 -u root -p ChineseAll -authenticationDatabase admin 3.2.8 mongo 125.39.193.168:27017 -u root -p ChineseAll -authenticationDatabase admin 阿里云VPC: mongo --host dds-2ze0d1069ce8ce442.mongodb.rds.aliyuncs.com:3717 --authenticationDatabase admin -u root -p ChineseAll _______________________________________________________________________________________________ MongoDB数据同步工具mongosync 2014-08-04 14:42:43 分类: NOSQL mongosync非常强大,可以实现mongodb之间迁移或者迁移至TokuMX,TokuMX版本对mongodb做了很多改进,我公司逐步用TokuMX来替换mongodb mongosync是什么 mongosync是用于MongoDB复制集之间,复制集到分片集群之间以及分片集群与分片集群之间同步数据的一个工具。 mongosync使用场景 1.实时迁移,尤其是从一个集群迁移到另一个集群,或者master-slave架构迁移到replica sets架构 2.实时同步,比如同步数据到其他集群。 3.其他场景 mongosync特点及功能增强 1.极速(ssd环境最大能达到百万每秒)、易用; 2.支持全量同步,增量同步,支持同步单库、单集合; 3.支持实时监测数据的变化并同步,类似tail -f效果,即使在同步过程中及以后新产生的数据也能同步到目标库; 4.支持MongoDB 1.8.x,MongoDB 2.0.x,MongoDB 2.4.x版本的同步, 支持master-slave到replica sets架构的同步, 支持replica sets到replica sets架构的同步, 支持replica sets到sharding cluster的同步; 集群间实时迁移方法: 直接使用mongosync 全量同步+增量同步功能同步数据到目标库(--oplog参数) 几个使用方法:(线上mongodb未采用权限控制,因为发现对性能有影响) 全量同步 mongosync -h 10.0.4.91:27017 --to 10.0.4.91:27020 增量同步 mongosync -h 10.0.4.91:27017 --to 10.0.4.91:27020 --oplog -s 1369406664,1 "初始化"同步(全量+增量+实时) mongosync -h 10.0.4.91:27017 --to 10.0.4.91:27020 --oplog 同步一段时间范围内的数据 mongosync -h 10.0.4.91:27017 --to 10.0.4.91:27020 --oplog -s 1369811325,1 -t 1369811373,1 ________________________________________________________________________________________________ 1.查看活动进程并关闭进程 > db.currentOp(); > // 等同于: db.$cmd.sys.inprog.findOne() { inprog: [{ "opid": 18, "op": "query", "ns": "mydb.votes", "query": "{ score : 1.0 }", "inLock": 1 }] } 字段说明: Opid: 操作进程号 Op: 操作类型(查询,更新等) Ns: 命名空间, 指操作的是哪个对象 Query: 如果操作类型是查询的话,这里将显示具体的查询内容 lockType: 锁的类型,指明是读锁还是写锁 结束进程: > db.killOp(1234/*opid*/) > // 等同于: db.$cmd.sys.killop.findOne({op:1234}) 注意:不要kill内部发起的操作,比如说replica set 发起的sync 操作等。 2.克隆collection 1)克隆远程colletion,使用cloneCollection命令完成将远程的collection复制到本地。 命令格式:db.runCommand({cloneCollection:"集合",from:"原机器",copyIndexes:false}),copyIndexes:是否复制索引 如: db.runCommand({cloneCollection:"test.t1",from:"132.42.33.175:28010"}) 2)克隆本地collection,mongodb没有提供命令进行本地复制,但我们可以写一个循环插入的方法完成, 例如:将source_collection中的数据复制一份到target_collection,代码如下: db.source_collection.find().forEach(function(x){db.target_collection.insert(x)}) 3.复制数据库,使用copyDatabase命令完成复制数据库, 格式:copyDatabase(fromdb,todb,fromhost[,username,password]) fromdb:源数据库名称 todb:目标数据库名称 fromhost:源数据库地址,本地和远程都可以 username:远程数据库用户名 password:远程数据密码 例子:将本地db2库复制本地,并重命名db1 > db.copyDatabase("db2","db1","localhost") 4.刷新磁盘 将内存中尚未写入磁盘的信息写入磁盘,并锁住对数据库更新的操作,但读操作可以使用,使用runCommand命令,这个命令只能在admin库上执行 格式:db.runCommand({fsync:1,async:true}) async:是否异步执行 lock:1 锁定数据库 5.数据压缩 mongodb的存储结构采用了预分配的机制,长期不断的操作,会留下太多的的碎片,从而导致数据库系统越来越慢。 repairDatabase命令是mongodb内置的一个方法,它会扫描数据库中的所有数据,并将通过导入/导出来重新整理数据集合,将碎片清理干净 现在看压缩前和压缩后的对比数据,如下所示: PRIMARY> db.t1.storageSize() 65232896 PRIMARY> db.t1.totalSize() 81470432 PRIMARY> db.repairDatabase() { "ok" : 1 } PRIMARY> db.t1.storageSize() 65232896 PRIMARY> db.t1.totalSize() 79851584 ________________________________________________________________________________________________ mongosync --host 125.39.195.125 -u mgr -p chineseall --to dds-2ze0d1069ce8ce441.mongodb.rds.aliyuncs.com:3717 --tu root --tp mongouser1 _________________________________________________________________________________________________ MongoDB数据同步工具mongosync http://nosqldb.org/p/5173d275cbce24580a033bd8 几个使用方法: 全量同步 mongosync -h 10.0.4.91:27017 -u admin -p 123 --to 10.0.4.91:27020 --tu admin --tp 456 增量同步 mongosync -h 10.0.4.91:27017 -u admin -p 123 --to 10.0.4.91:27020 --tu admin --tp 456 --oplog -s 1369406664,1 “初始化”同步(全量+增量+实时) mongosync -h 10.0.4.91:27017 -u admin -p 123 --to 10.0.4.91:27020 --tu admin --tp 456 --oplog 同步一段时间范围内的数据 mongosync -h 10.0.4.91:27017 -u admin -p 123 --to 10.0.4.91:27020 --tu admin --tp 456 --oplog -s 1369811325,1 -t 1369811373,1 __________________________________________________________________________________________________ db.fs.files.find({filename:/xxx/}).forEach(function(n) {db.fs.files.update({filename:u.filename},{$set:{filename:newname}},false,true)}} //正则批量更改为固定名称,便于删除。 mongofiles -port 12345 -d xxx delete newname //mongofies根据filename批量干掉这些文件。 db.repairDatabase() //特别注意以上删除不是物理删除,chunks文件实际还在,show dbs 或者 db.stats() 发现db的size没有变化,要执行db.repairDatabase();另外注意这个动作是全局写锁,很耗内存和cpu的,而且处理时间跟文件数量大小有关,务必在非高峰期做。 ___________________________________________________________________________________________________ ubuntu 12.04 升级 mongodb 3.2 $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 $ echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list $ sudo apt-get update $ sudo apt-get install -y mongodb-org=3.2.6 mongodb-org-server=3.2.6 mongodb-org-shell=3.2.6 mongodb-org-mongos=3.2.6 mongodb-org-tools=3.2.6 $ sudo apt-get install -y mongodb-org-shell ____________________________________________________________________________________________________ Mongo数据库添加用户 //切换数据库 use mydb //添加用户 db.addUser("test","123456"); //认证用户 db.auth("test","123456"); //查看用户是否添加 db.system.users.find(); //切换数据库 use bi_test //添加用户 db.createUser({user:"admin",pwd:"123456",roles:["dbAdmin","readWrite"]}) //认证用户 db.grantRolesToUser ("admin",{role:"readWrite",db:"bi_test"}) //查看用户是否添加 db.system.users.find(); db.grantRolesToUser ("test",[{role: "read", db: "testdb"},{role: "read", db: "admin"},{role: "backup", db: "admin"},{role: "read", db: "local"}] ) db.grantRolesToUser ("test",{role:"readWrite",db:"testdb"}) db.createUser({user:"mongo",pwd:"123456",roles:["dbAdmin","readWrite"]}) use admin db.auth('root', '123456') mongo 192.168.11.6:27017 -u root -p 123456 –authenticationDatabase admin use admin db.createUser({user:"root",pwd:"ChineseAll",roles:["dbAdmin","readWrite"]}) db.auth('root', 'ChineseAll') db.grantRolesToUser ("root",[{role: "read", db: "mydb"},{role: "read", db: "admin"},{role: "backup", db: "admin"},{role: "read", db: "local"}] ) ## bi_test 库授权 use admin db.createUser({user:"admin",pwd:"123456",roles:["dbAdmin","readWrite"]}) db.auth('admin', '123456') db.grantRolesToUser ("admin",[{role: "read", db: "bi_test"},{role: "read", db: "admin"},{role: "read", db: "local"}] ) use admin db.createUser({user:"root",pwd:"123456",roles:["dbAdmin","readWrite"]}) db.auth('root', '123456') db.grantRolesToUser ("root",[{role: "read", db: "mydb"},{role: "read", db: "admin"},{role: "backup", db: "admin"},{role: "read", db: "local"}] ) _____________________________________________________________________________________________________ 文档仓库 统一数据平台 蓝光塔 sony 4光头 孙致力 王雅明 web + 中间件 4层 vlm session manager 去 cluster 化 send manager 单点登录 认证 支持ldap协议 redis 内存数据库 4U 48个刀 HP 服务器 淘宝绿色开源服务器 DSP 服务器 HP GPU集群 rsconf = { _id: "rs01", members: [ { _id: 0, host: "v-mongodb-node-04" } ] } 上线并行运行 ______________________________________________________________________________________________________ 创建集群密钥文件 # openssl rand -base64 753 --keyFile keyfile rsconf = { _id: "rs01", members: [ { _id: 0, host: "v-mongodb-06" } ] } mongo> rs.initiate( rsconf ) mongo> rs.add("v-mongodb-07:27018") mongo> rs.add("v-mongodb-08:27018") rs.initiate() rs.conf() rs.reconfig() rs.add() mongos> sh.addShard("rs01/v-mongodb-06,v-mongodb-07,v-mongodb-08") mongos> sh.addShard("rs02/v-mongodb-09,v-mongodb-10,v-mongodb-11") mongos> sh.addShard("rs03/v-mongodb-12,v-mongodb-13,v-mongodb-14") mongos> sh.enableSharding("test") mongos> db.runCommand( {listshards : 1 } ) _________________________________________________________________________________________________________ 1、Create a http://docs.mongodb.org/manual/etc/yum.repos.d/10gen.repo file to hold informa- tion about your repository. If you are running a 64-bit system (recommended,) place the following configuration in http://docs.mongodb.org/manual/etc/yum.repos.d/10gen.repo file: [10gen] name=10gen Repository baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64 gpgcheck=0 enabled=1 If you are running a 32-bit system, which isn’t recommended for production deployments, place the following config- uration in http://docs.mongodb.org/manual/etc/yum.repos.d/10gen.repo file: [10gen] name=10gen Repository baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686 gpgcheck=0 enabled=1 2、Install Packages Issue the following command (as root or with sudo) to install the latest stable version of MongoDB and the associ- ated tools: # yum install mongo-10gen mongo-10gen-server # yum install mongo-10gen-2.2.3 mongo-10gen-server-2.2.3 bind_ip=mongodb01,localhost ________________________________________________________________________________________________ MongoDB基本管理命令 MongoDB是一个NoSQL数据库系统:一个数据库可以包含多个集合(Collection),每个集合对应于关系数据库中的表;而每个集合中可以存储一组由列标识的记录,列是可以自由定义的,非常灵活,由一组列标识的实体的集合对应于关系数据库表中的行。下面通过熟悉MongoDB的基本管理命令,来了解MongoDB提供的DBMS的基本功能和行为。 MongoDB命令帮助系统 在安装MongoDB后,启动服务器进程(mongod),可以通过在客户端命令mongo实现对MongoDB的管理和监控。看一下MongoDB的命令帮助系统: [plain] view plain copy root@dev2:~# mongo MongoDB shell version: 1.8.3 connecting to: test > help db.help() help on db methods db.mycoll.help() help on collection methods rs.help() help on replica set methods help connect connecting to a db help help admin administrative help help misc misc things to know help mr mapreduce help 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 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 这是MongoDB最顶层的命令列表,主要告诉我们管理数据库相关的一些抽象的范畴:数据库操作帮助、集合操作帮助、管理帮助。如果你想了解数据库操作更详细的帮助命令,可以直接使用db.help(),如下所示: [plain] view plain copy > db.help() DB methods: db.addUser(username, password[, readOnly=false]) 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 the current operation in the db db.dropDatabase() db.eval(func, args) run code server-side 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 this connection to read from the nonmaster member of a replica pair 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.isMaster() check replica primary status db.killOp(opid) kills the current operation in the db db.listCommands() lists all the db commands db.printCollectionStats() db.printReplicationInfo() db.printSlaveReplicationInfo() db.printShardingStatus() 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.shutdownServer() db.stats() db.version() current version of the server db.getMongo().setSlaveOk() allow queries on a replication slave server 对数据库进行管理和操作的基本命令,可以从上面获取到。如果想要得到更多,而且每个命令的详细用法,可以使用上面列出的db.listCommands()查询。 另一个比较基础的是对指定数据库的集合进行操作、管理和监控,可以通过查询db.mycoll.help()获取到: [plain] view plain copy > db.mycoll.help() DBCollection help db.mycoll.find().help() - show DBCursor help db.mycoll.count() db.mycoll.dataSize() db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' ) db.mycoll.drop() drop the collection db.mycoll.dropIndex(name) db.mycoll.dropIndexes() db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups 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]) db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) db.mycoll.getDB() get DB object associated with collection db.mycoll.getIndexes() db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> ) db.mycoll.remove(query) db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection. db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name db.mycoll.save(obj) db.mycoll.stats() 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]) db.mycoll.validate() - SLOW db.mycoll.getShardVersion() - only for use with sharding 有关数据库和集合管理的相关命令,是最基础和最常用的,如集合查询、索引操作等。 基本命令及实例 下面通过实际的例子来演示一些常见的命令: (一)基本命令 1、show dbs 显示当前数据库服务器上的数据库 2、use pagedb 切换到指定数据库pagedb的上下文,可以在此上下文中管理pagedb数据库以及其中的集合等 3、show collections 显示数据库中所有的集合(collection) 4、db.serverStatus() 查看数据库服务器的状态。示例如下所示: [plain] view plain copy { "host" : "dev2", "version" : "1.8.3", "process" : "mongod", "uptime" : 845446, "uptimeEstimate" : 839192, "localTime" : ISODate("2011-12-27T04:03:12.512Z"), "globalLock" : { "totalTime" : 845445636925, "lockTime" : 13630973982, "ratio" : 0.016122827283818857, "currentQueue" : { "total" : 0, "readers" : 0, "writers" : 0 }, "activeClients" : { "total" : 0, "readers" : 0, "writers" : 0 } }, "mem" : { "bits" : 64, "resident" : 12208, "virtual" : 466785, "supported" : true, "mapped" : 466139 }, "connections" : { "current" : 27, "available" : 792 }, "extra_info" : { "note" : "fields vary by platform", "heap_usage_bytes" : 70895216, "page_faults" : 17213898 }, "indexCounters" : { "btree" : { "accesses" : 4466653, "hits" : 4465526, "misses" : 1127, "resets" : 0, "missRatio" : 0.00025231420484197006 } }, "backgroundFlushing" : { "flushes" : 14090, "total_ms" : 15204393, "average_ms" : 1079.0910574875797, "last_ms" : 669, "last_finished" : ISODate("2011-12-27T04:02:28.713Z") }, "cursors" : { "totalOpen" : 3, "clientCursors_size" : 3, "timedOut" : 53 }, "network" : { "bytesIn" : 63460818650, "bytesOut" : 763926196104, "numRequests" : 67055921 }, "opcounters" : { "insert" : 7947057, "query" : 35720451, "update" : 16263239, "delete" : 154, "getmore" : 91707, "command" : 68520 }, "asserts" : { "regular" : 0, "warning" : 1, "msg" : 0, "user" : 7063866, "rollovers" : 0 }, "writeBacksQueued" : false, "ok" : 1 } 有时,通过查看数据库服务器的状态,可以判断数据库是否存在问题,如果有问题,如数据损坏,可以及时执行修复。 5、查询指定数据库统计信息 use fragment db.stats() 查询结果示例如下所示: [plain] view plain copy > db.stats() { "db" : "fragment", "collections" : 12, "objects" : 384553, "avgObjSize" : 3028.40198360174, "dataSize" : 1164581068, "storageSize" : 1328351744, "numExtents" : 109, "indexes" : 10, "indexSize" : 16072704, "fileSize" : 4226809856, "ok" : 1 } 显示fragment数据库的统计信息。 6、查询指定数据库包含的集合名称列表 db.getCollectionNames() 结果如下所示: [plain] view plain copy > db.getCollectionNames() [ "17u", "baseSe", "bytravel", "daodao", "go2eu", "lotour", "lvping", "mafengwo", "sina", "sohu", "system.indexes" ] (二)基本DDL和DML 1、创建数据库 如果你习惯了关系型数据库,你可能会寻找相关的创建数据库的命令。在MongoDB中,你可以直接通过use dbname来切换到这个数据库上下文下面,系统会自动延迟创建该数据库,例如: [plain] view plain copy > show dbs admin 0.03125GB local (empty) pagedb 0.03125GB test 0.03125GB > use LuceneIndexDB switched to db LuceneIndexDB > show dbs admin 0.03125GB local (empty) pagedb 0.03125GB test 0.03125GB > db LuceneIndexDB > db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'}) > show dbs LuceneIndexDB 0.03125GB admin 0.03125GB local (empty) pagedb 0.03125GB test 0.03125GB > 可见,在use指定数据库后,并且向指定其中的一个集合并插入数据后,数据库和集合都被创建了。 2、删除数据库 直接使用db.dropDatabase()即可删除数据库。 3、创建集合 可以使用命令db.createCollection(name, { size : ..., capped : ..., max : ... } )创建集合,示例如下所示: [plain] view plain copy > db.createCollection('mgr', {'capped':true, 'size':10240, 'max':17855200}) { "ok" : 1 } > show collections replicationColletion storeCollection system.indexes 4、删除集合 删除集合,可以执行db.mycoll.drop()。 5、插入更新记录 直接使用集合的save方法,如下所示: [plain] view plain copy > <em>db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})</em> 更新记录,使用save会将原来的记录值进行覆盖实现记录更新。 6、查询一条记录 使用findOne()函数,参数为查询条件,可选,系统会随机查询获取到满足条件的一条记录(如果存在查询结果数量大于等于1)示例如下所示: [plain] view plain copy > db.storeCollection.findOne({'version':'3.5'}) { "_id" : ObjectId("4ef970f23c1fc4613425accc"), "version" : "3.5", "segment" : "e3ol6" } 7、查询多条记录 使用find()函数,参数指定查询条件,不指定条件则查询全部记录。 8、删除记录 使用集合的remove()方法,参数指定为查询条件,示例如下所示: [plain] view plain copy > db.storeCollection.remove({'version':'3.5'}) > db.storeCollection.findOne() null 9、创建索引 可以使用集合的ensureIndex(keypattern[,options])方法,示例如下所示: [plain] view plain copy > use pagedb switched to db pagedb > db.page.ensureIndex({'title':1, 'url':-1}) > db.system.indexes.find() { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 } { "name" : "_id_", "ns" : "pagedb.system.users", "key" : { "_id" : 1 }, "v" : 0} { "_id" : ObjectId("4ef977633c1fc4613425accd"), "ns" : "pagedb.page", "key" : {"title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "v" : 0 } 上述,ensureIndex方法参数中,数字1表示升序,-1表示降序。 使用db.system.indexes.find()可以查询全部索引。 10、查询索引 我们为集合建立的索引,那么可以通过集合的getIndexes()方法实现查询,示例如下所示: [plain] view plain copy > db.page.getIndexes() [ { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 }, { "_id" : ObjectId("4ef977633c1fc4613425accd"), "ns" : "pagedb.page", "key" : { "title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "v" : 0 } ] 当然,如果需要查询系统中全部的索引,可以使用db.system.indexes.find()函数。 11、删除索引 删除索引给出了两个方法: [plain] view plain copy db.mycoll.dropIndex(name) db.mycoll.dropIndexes() 第一个通过指定索引名称,第二个删除指定集合的全部索引。 12、索引重建 可以通过集合的reIndex()方法进行索引的重建,示例如下所示: [plain] view plain copy > db.page.reIndex() { "nIndexesWas" : 2, "msg" : "indexes dropped for collection", "ok" : 1, "nIndexes" : 2, "indexes" : [ { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 }, { "_id" : ObjectId("4ef977633c1fc4613425accd"), "ns" : "pagedb.page", "key" : { "title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "v" : 0 } ], "ok" : 1 } 13、统计集合记录数 use fragment db.baseSe.count() 统计结果,如下所示: [plain] view plain copy > use fragment switched to db fragment > db.baseSe.count() 36749 上述统计了数据库fragment的baseSe集合中记录数。 14、查询并统计结果记录数 use fragment db.baseSe.find().count() find()可以提供查询参数,然后查询并统计结果,如下所示: [plain] view plain copy > use fragment switched to db fragment > db.baseSe.find().count() 36749 上述执行先根据查询条件查询结果,然后统计了查询数据库fragment的baseSe结果记录集合中记录数。 15、查询指定数据库的集合当前可用的存储空间 use fragment > db.baseSe.storageSize() 142564096 16、查询指定数据库的集合分配的存储空间 > db.baseSe.totalSize() 144096000 上述查询结果中,包括为集合(数据及其索引存储)分配的存储空间。 (三)启动与终止 1、正常启动 mongod --dbpath /usr/mongo/data --logfile /var/mongo.log 说明: 指定数据存储目录和日志目录,如果采用安全认证模式,需要加上--auth选项,如: mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log 2、以修复模式启动 mongod --repair 以修复模式启动数据库。 实际很可能数据库数据损坏或数据状态不一致,导致无法正常启动MongoDB服务器,根据启动信息可以看到需要进行修复。或者执行: mongod -f /etc/mongodb.conf --repair 3、终止服务器进程 db.shutdownServer() 终止数据库服务器进程。或者,可以直接kill掉mongod进程即可。 (四)安全管理 1、以安全认证模式启动 mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log 使用--auth选项启动mongod进程即可启用认证模式。 或者,也可以修改/etc/mongodb.conf,设置auth=true,重启mongod进程。 2、添加用户 db.addUser("admin", ",%F23_kj~00Opoo0+\/") 添加数据库用户,添加成功,则显示结果如下所示: [plain] view plain copy { "user" : "admin", "readOnly" : false, "pwd" : "995d2143e0bf79cba24b58b3e41852cd" } 3、安全认证 db.auth("admin", ",%F23_kj~00Opoo0+\/") 数据库安全认证。认证成功显示结果: [plain] view plain copy { "user" : "admin", "readOnly" : false, "pwd" : "995d2143e0bf79cba24b58b3e41852cd" } 如果是认证用户,执行某些命令,可以看到正确执行结果,如下所示: [plain] view plain copy db.system.users.find() { "_id" : ObjectId("4ef940a13c1fc4613425acc8"), "user" : "admin", "readOnly" : false, "pwd" : "995d2143e0bf79cba24b58b3e41852cd" } 否则,认证失败,则执行相关命令会提示错误: [plain] view plain copy db.system.users.find() error: { "$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1", "code" : 10057 } 4、为数据库写数据(同步到磁盘)加锁 db.runCommand({fsync:1,lock:1}) 说明: 该操作已经对数据库上锁,不允许执行写数据操作,一般在执行数据库备份时有用。执行命令,结果示例如下: [plain] view plain copy { "info" : "now locked against writes, use db.$cmd.sys.unlock.findOne() to unlock", "ok" : 1 } 5、查看当前锁状态 db.currentOp() 说明: 查询结果如下所示: [plain] view plain copy { "inprog" : [ ], "fsyncLock" : 1, "info" : "use db.$cmd.sys.unlock.findOne() to terminate the fsync write/snapshot lock" } 其中,fsyncLock为1表示MongoDB的fsync进程(负责将写入改变同步到磁盘)不允许其他进程执行写数据操作 6、解锁 use admin db.$cmd.sys.unlock.findOne() 说明: 执行解锁,结果如下所示: [plain] view plain copy { "ok" : 1, "info" : "unlock requested" } 可以执行命令查看锁状态: db.currentOp() 状态信息如下: [plain] view plain copy { "inprog" : [ ] } 说明当前没有锁,可以执行写数据操作。 (五)数据备份、恢复与迁移管理 1、备份全部数据库 mkdir testbak cd testbak mongodump 说明:默认备份目录及数据文件格式为./dump/[databasename]/[collectionname].bson 2、备份指定数据库 mongodump -d pagedb 说明:备份数据库pagedb中的数据。 3、备份一个数据库中的某个集合 mongodump -d pagedb -c page 说明:备份数据库pagedb的page集合。 4、恢复全部数据库 cd testbak mongorestore --drop 说明:将备份的所有数据库恢复到数据库,--drop指定恢复数据之前删除原来数据库数据,否则会造成回复后的数据中数据重复。 5、恢复某个数据库的数据 cd testbak mongorestore -d pagedb --drop 说明:将备份的pagedb的数据恢复到数据库。 6、恢复某个数据库的某个集合的数据 cd testbak mongorestore -d pagedb -c page --drop 说明:将备份的pagedb的的page集合的数据恢复到数据库。 7、向MongoDB导入数据 mongoimport -d pagedb -c page --type csv --headerline --drop < csvORtsvFile.csv 说明:将文件csvORtsvFile.csv的数据导入到pagedb数据库的page集合中,使用cvs或tsv文件的列名作为集合的列名。需要注意的是,使用--headerline选项时,只支持csv和tsv文件。 --type支持的类型有三个:csv、tsv、json 其他各个选项的使用,可以查看帮助: [plain] view plain copy mongoimport --help options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb if dbpath specified, each db is in a separate directory -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) -f [ --fields ] arg comma separated list of field names e.g. -f name,age --fieldFile arg file with fields names - 1 per line --ignoreBlanks if given, empty fields in csv and tsv will be ignored --type arg type of file to import. default: json (json,csv,tsv) --file arg file to import from; if not specified stdin is used --drop drop collection first --headerline CSV,TSV only - use first line as headers --upsert insert or update objects that already exist --upsertFields arg comma-separated fields for the query part of the upsert. You should make sure this is indexed --stopOnError stop importing at first error rather than continuing --jsonArray load a json array, not one item per line. Currently limited to 4MB. 8、从向MongoDB导出数据 mongoexport -d pagedb -c page -q {} -f _id,title,url,spiderName,pubDate --csv > pages.csv 说明:将pagedb数据库中page集合的数据导出到pages.csv文件,其中各选项含义: -f 指定cvs列名为_id,title,url,spiderName,pubDate -q 指定查询条件 其他各个选项的使用,可以查看帮助: [plain] view plain copy mongoexport --help options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb if dbpath specified, each db is in a separate directory -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) -f [ --fields ] arg comma separated list of field names e.g. -f name,age --fieldFile arg file with fields names - 1 per line -q [ --query ] arg query filter, as a JSON string --csv export to csv instead of json -o [ --out ] arg output file; if not specified, stdout is used --jsonArray output to a json array rather than one object per line 注意: 如果上面的选项-q指定一个查询条件,需要使用单引号括起来,如下所示: [plain] view plain copy mongoexport -d page -c Article -q '{"spiderName": "mafengwoSpider"}' -f _id,title,content,images,publishDate,spiderName,url --jsonArray > mafengwoArticle.txt 否则,就会出现下面的错误: [plain] view plain copy ERROR: too many positional options (六)远程连接管理 1、基于mongo实现远程连接 [plain] view plain copy mongo -u admin -p admin 192.168.0.197:27017/pagedb 通过mongo实现连接,可以非常灵活的选择参数选项,参看命令帮助,如下所示: [plain] view plain copy mongo --help MongoDB shell version: 1.8.3 usage: mongo [options] [db address] [file names (ending in .js)] db address can be: foo foo database on local machine 192.169.0.5/foo foo database on 192.168.0.5 machine 192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999 options: --shell run the shell after executing files --nodb don't connect to mongod on startup - no 'db address' arg expected --quiet be less chatty --port arg port to connect to --host arg server to connect to --eval arg evaluate javascript -u [ --username ] arg username for authentication -p [ --password ] arg password for authentication -h [ --help ] show this usage information --version show version information --verbose increase verbosity --ipv6 enable IPv6 support (disabled by default) 2、基于MongoDB支持的javascript实现远程连接 当你已经连接到一个远程的MongoDB数据库服务器(例如,通过mongo连接到192.168.0.184),现在想要在这个会话中连接另一个远程的数据库服务器(192.168.0.197),可以执行如下命令: [plain] view plain copy > var x = new Mongo('192.168.0.197:27017') > var ydb = x.getDB('pagedb'); > use ydb switched to db ydb > db ydb > ydb.page.findOne() { "_id" : ObjectId("4eded6a5bf3bfa0014000003"), "content" : "巴黎是浪漫的城市,可是...", "pubdate" : "2006-03-19", "title" : "巴黎:从布鲁塞尔赶到巴黎", "url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html" } 上述通过MongoDB提供的JavaScript脚本,实现对另一个远程数据库服务器进行连接,操作指定数据库pagedb的page集合。 如果启用了安全认证模式,可以在获取数据库连接实例时,指定认证账号,例如: [plain] view plain copy > var x = new Mongo('192.168.0.197:27017') > var ydb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3'); > use ydb switched to db ydb
docker-compose.yml
Etcd
0
赞
1 人读过
新浪微博
微信
更多分享
腾讯微博
QQ空间
人人网
文档导航