mongo常用命令

索引
普通索引
1、唯一索引
db.posts.ensureIndex({ slug: 1 })
查询: db.posts.find({ slug : 'state-of-mongodb-2010' })
索引:db.posts.ensureIndex({ slug: 1 }, {unique: true});

2、组合索引
  查询: db.comments.find({ tags : 'mongodb'}).sort({ created_at : -1 });
索引: db.comments.ensureIndex({tags : 1, created_at : -1});

查询数据用指定索引hint

db.person.find({tags:'tags',created_at:'created_at'}).hint({tags:1,created_at:1})

查询索引
db.posts.getIndexes()

查看索引大小
db.comments.totalIndexSize();

删除索引
db.comments.dropIndex("name_1")

通常需要索引的字段是:
1.唯一键 _id 是默认被设置为索引的
2.需要被查找的字段应该建立索引,比如在find()里面的字段
3.需要被排序的字段应该建立索引。比如在sort()里面的字段

<1> count
db.user.count()
db.user.count({'age':20})
<2> distinct

db.user.distinct('user')
<3> group
db.pal.group({'key':{'pal':true},'initial':{'pal':[]},'$reduce':function(cur,prev){prev.pal.push(cur.pal);}})

db.pal.group({'key':{'pal':true},'initial':{'pal':[]},'$reduce':function(cur,prev){prev.pal.push(cur.pal);},'finalize':function(out){out.count=out.person.length;},'condition':{'age':{$lt:25}}})

<4> mapReduce



导出数据
mongoexport -d qnmsg -c msg -o msg.dat
-d 指明使用的库, 本例中为” my_mongodb”
-c 指明要导出的表, 本例中为”user”
-o 指明要导出的文件名, 本例中为”user.dat”
从上面可以看到导出的方式使用的是JSON 的样式

mongoexport -d qnlbs -c user --csv -f userID,age -o user_csv.dat
-csv 指要要导出为csv 格式
 -f 指明需要导出哪些例


数据导入mongoimport
mongoimport -d qnmsg -c msg pal.msg

mongoimport -d qnlbs -c user --type csv user.cvs

mongoimport -d qnmsg -c pal --type csv --headerline --file /root/bak/test.csv --host md02:30000



主从复制
第一步:我们把mongodb文件夹放在D盘和E盘,模拟放在多服务器上。

第二步:启动D盘上的mongodb,把该数据库指定为主数据库,其实命令很简单:>mongodb --dbpath='XXX' --master,

           端口还是默认的27017.
第三步:同样的方式启动E盘上的mongodb,指定该数据库为从属数据库,命令也很简单,当然我们要换一个端口,比如:8888。

           source 表示主数据库的地址。

           >mongod --dbpath=xxxx --port=8888 --slave --source=127.0.0.1:27017
          
          
副本集
第一步:  既然我们要建立集群,就得取个集群名字,这里就取我们的公司名shopex, --replSet表示让服务器知道shopex下还有其他数据库,

            这里就把D盘里面的mongodb程序打开,端口为2222。指定端口为3333是shopex集群下的另一个数据库服务器。 
           
         mongod --dbpath=D:\mongodb\db --port 2222 --replSet shopex/127.0.0.1:3333
         第二步:  既然上面说3333是另一个数据库服务器,不要急,现在就来开,这里把E盘的mongodb程序打开。
        
          mongod --dbpath=D:\mongodb\db --port 3333 --replSet shopex/127.0.0.1:2222
         
          第三步:  ok,看看上面的日志红色区域,似乎我们还没有做完,是的,log信息告诉我们要初始化一下“副本集“,既然日志这么说,那我也就

             这么做,随便连接一下哪个服务器都行,不过一定要进入admin集合。
            
             mongo 127.0.0.1:2222
             use admin
             db.runCommand({'replSetinitiate':{'_id':'shopex','members':[
             {'_id':1,'host':'127..0.0.1:2222'},
             {'_id':2,'host':'127..0.0.1:3333'}
             ]}})
             第四步: 开启成功后,我们要看看谁才能成为主数据库服务器,可以看到端口为2222的已经成为主数据库服务器。
            
             第五步:我们知道sql server里面有一个叫做仲裁服务器,那么mongodb中也是有的,跟sql server一样,仲裁只参与投票选举,这里我们

           把F盘的mongodb作为仲裁服务器,然后指定shopex集群中的任一个服务器端口,这里就指定2222。
           mongod --dbpath=F:\mongodb\db --port 4444 --replSet shopex/127.0.0.1:2222
          
           然后我们在admin集合中使用rs.addArb()追加即可。
             mongo 127.0.0.1:2222/admin
             rs.addArb('127.0.0.1:4444')
             追加好了之后,我们使用rs.status()来查看下集群中的服务器状态,图中我们可以清楚的看到谁是主,还是从,还是仲裁。
            
            
            
            
mongoexport -d new_q -c openapps_visitlog -q '{request_time:{$gte:new Date(1334592000000)}}' -o  /home/oracle/openapps_visitlog.js        
            
mongoexport  -h "127.0.0.1" -d qnlbs -c user -csv -o test1.csv -q '{"img":{"$ne":""}}' -f userID,uname,email,sex,birthday,age,img,photo.mypto

           
mongoimport -d test -c user --type csv --headerline --file /qn/test1.csv          
           
           
     db.power.distinct("userID").length
查看keyword表中keyword字段没有重复的记录总数










数据备份mongodump
./mongodump -d my_mongodb
此时会在当前目录下创建一个dump 目录,用于存放备份出来的文件
也可以指定备份存放的目录,
./mongodump -d my_mongodb -o my_mongodb_dump
这个例子中将备份的文件存在了当前目录下的my_mongodb_dump 目录下

数据恢复mongorestore
由于刚刚已经做了备份,所以我们先将库my_mongodb 删除掉
  use my_mongodb
  db.dropDatabase()
 
  ./mongorestore -d my_mongodb my_mongodb_dump/*
 
 
  mongodump  -d qnlbs
 
 
 
 
 
 
 
  Profiler默认是关闭的,你可以选择全部开启,或者有慢查询的时候开启。
  慢查询开启:
  db.setProfilingLevel(2);
db.getProfilingLevel()
查看Profile日志
db.system.profile.find().sort({$natural:-1})
MongoDB Monitoring Service(MMS)是Mongodb厂商提供的监控服务,可以在网页和Android客户端上监控你的MongoDB状况。








  db.help();
DB methods:
        db.addUser(username, password) 添加数据库授权用户
        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()
        db.getReplicationInfo()
        db.getSisterDB(name) get the db at the same server as this onew
        db.killOp() kills the current operation in the db
        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.setProfilingLevel(level) 0=off 1=slow 2=all
        db.shutdownServer ()
        db.version() current version of the server
       
       
       
        db.user.help();  user为表名
DBCollection help
        db.foo.count()                统计表的行数
        db.foo.dataSize()        统计表数据的大小
        db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重
        db.foo.drop() drop the collection 删除表
        db.foo.dropIndex(name)  删除指定索引
        db.foo.dropIndexes() 删除所有索引
        db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增加索引
        db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return. 根据条件查找数据
                                           e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } )
        db.foo.find(...).count()
        db.foo.find(...).limit(n) 根据条件查找数据并返回指定记录数
        db.foo.find(...).skip(n)
        db.foo.find(...).sort(...) 查找排序
        db.foo.findOne([query]) 根据条件查询只查询一条数据
        db.foo.getDB() get DB object associated with collection  返回表所属的库
        db.foo.getIndexes() 显示表的所有索引
        db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组
        db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.foo.remove(query) 根据条件删除数据
        db.foo.renameCollection( newName ) renames the collection  重命名表
        db.foo.save(obj) 保存数据
        db.foo.stats()  查看表的状态
        db.foo.storageSize() - includes free space allocated to this collection 查询分配到表空间大小
        db.foo.totalIndexSize() - size in bytes of all the indexes 查询所有索引的大小
        db.foo.totalSize() - storage allocated for all data and indexes 查询表的总大小
        db.foo.update(query, object[, upsert_bool]) 根据条件更新数据
        db.foo.validate() - SLOW 验证表的详细信息
        db.foo.getShardVersion() - only for use with sharding
      
           
           
               

你可能感兴趣的:(mongo常用命令)