chenkehao 发表于 2018-10-26 09:43:04

mongodb 命令相关

  一.更新删除
  db.orders.update({"pi_code":57,"money":10},{$set:{"money":"9.5"}},false,true)
  db.orders.remove({"completeTime":{$lt : 1435791982}})
  mongodbnosqlupdate数据更新更新操作符
  Mongodb更新有两个命令:update、save。
  1.1update命令
  update命令格式:
  db.collection.update(criteria,objNew,upsert,multi)
  参数说明:
  criteria:查询条件
  objNew:update对象和一些更新操作符
  upsert:如果不存在update的记录,是否插入objNew这个新的文档,true为插入,默认为false,不插入。
  multi:默认是false,只更新找到的第一条记录。如果为true,把按条件查询出来的记录全部更新。
  示例:
  Shell代码
  1.> db.classes.insert({"name":"c1","count":30})
  2.> db.classes.insert({"name":"c2","count":30})
  3.> db.classes.find()
  4.{ "_id" : ObjectId("5030f3a3721e16c4ab180cd9"), "name" : "c1", "count" : 30 }
  5.{ "_id" : ObjectId("5030f3ab721e16c4ab180cda"), "name" : "c2", "count" : 30 }
  6.>
  示例1:把count大于20的class name修改为c3
  Shell代码
  1.> db.classes.update({"count":{$gt:20}},{$set:{"name":"c3"}})
  2.> db.classes.find()
  3.{ "_id" : ObjectId("5030f3a3721e16c4ab180cd9"), "name" : "c3", "count" : 30 }
  4.{ "_id" : ObjectId("5030f3ab721e16c4ab180cda"), "name" : "c2", "count" : 30 }
  5.>
  由于没有指定upsert和multi的值,所以全部默认为false,由结果可以看出,只修改了第一条符合条件的记录。
  示例2:把count大于20的class name修改为c4,设置multi为true
  Shell代码
  1.> db.classes.update({"count":{$gt:20}},{$set:{"name":"c4"}},false,true)
  2.> db.classes.find()
  3.{ "_id" : ObjectId("5030f3a3721e16c4ab180cd9"), "name" : "c4", "count" : 30 }
  4.{ "_id" : ObjectId("5030f3ab721e16c4ab180cda"), "name" : "c4", "count" : 30 }
  5.>
  由于指定了multi为true,所以对两条符合条件的记录都进行了更新。
  示例3: 把count大于50的class name修改为c5,设置upsert为true
  Shell代码
  1.> db.classes.update({"count":{$gt:50}},{$set:{"name":"c5"}},true,false)
  2.> db.classes.find()
  3.{ "_id" : ObjectId("5030f3a3721e16c4ab180cd9"), "name" : "c4", "count" : 30 }
  4.{ "_id" : ObjectId("5030f3ab721e16c4ab180cda"), "name" : "c4", "count" : 30 }
  5.{ "_id" : ObjectId("5030f589ce8fa8884e6cd441"), "name" : "c5" }
  6.>
  在集合中没有count大于50的记录,但是由于指定了upsert为true,如果找不到则会插入一条新记录。
  1.2save命令
  Mongodb另一个更新命令是save,格式如下:
  db.collection.save(obj)
  obj代表需要更新的对象,如果集合内部已经存在一个和obj相同的"_id"的记录,Mongodb会把obj对象替换集合内已存在的记录,如果不存在,则会插入obj对象。
  这条命令比较简单,示例就省略了。
  二、数据更新操作符
  1.$inc
  用法:{$inc:{field:value}}
  作用:对一个数字字段的某个field增加value
  示例:将name为chenzhou的学生的age增加5
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou", "age" : 22 }
  3.#查询结果显示年龄为22
  4.> db.students.update({name:"chenzhou"},{$inc:{age:5}})
  5.#执行修改,把age增加5
  6.> db.students.find()
  7.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou", "age" : 27 }
  8.>
  9.#查询结果显示年龄为27,修改成功
  2.$set
  用法:{$set:{field:value}}
  作用:把文档中某个字段field的值设为value
  示例: 把chenzhou的年龄设为23岁
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou", "age" : 27 }
  3.> db.students.update({name:"chenzhou"},{$set:{age:23}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou", "age" : 23 }
  6.>
  从结果可以看到,更新后年龄从27变成了23
  3.$unset
  用法:{$unset:{field:1}}
  作用:删除某个字段field
  示例: 将chenzhou的年龄字段删除
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou", "age" : 23 }
  3.> db.students.update({name:"chenzhou"},{$unset:{age:1}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou" }
  6.>
  4.$push
  用法:{$push:{field:value}}
  作用:把value追加到field里。注:field只能是数组类型,如果field不存在,会自动插入一个数组类型
  示例:给chenzhou添加别名"michael"
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$push:{"ailas":"Michael"}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael" ], "name" : "chenzhou" }
  6.>
  由结果可以看到,记录中追加了一个数组类型字段alias,且字段有一个为"Michael"的值
  5.pushAll
  用法:{$pushAll:{field:value_array}}
  作用:用法同$push一样,只是$pushAll可以一次追加多个值到一个数组字段内。
  示例:给chenzhou追加别名A1,A2
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael" ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$pushAll:{"ailas":["A1","A2"]}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael", "A1", "A2" ], "name" : "chenzhou" }
  6.>
  6.$addToSet
  用法:{$addToSet:{field:value}}
  作用:加一个值到数组内,而且只有当这个值在数组中不存在时才增加。
  示例:往chenzhou的别名字段里添加两个别名A3、A4
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael", "A1", "A2" ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$addToSet:{"ailas":["A3","A4"]}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael", "A1", "A2", [ "A3", "A4" ] ], "name" : "chenzhou" }
  6.>
  由结果可以看出,更新后ailas字段里多了一个对象,这个对象里包含2个数据,分别是A3、A4
  7.$pop
  用法:删除数组内第一个值:{$pop:{field:-1}}、删除数组内最后一个值:{$pop:{field:1}}
  作用:用于删除数组内的一个值
  示例: 删除chenzhou记录中alias字段中第一个别名
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "Michael", "A1", "A2", [ "A3", "A4" ] ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$pop:{"ailas":-1}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A1", "A2", [ "A3", "A4" ] ], "name" : "chenzhou" }
  6.>
  由结果可以看书,第一个别名Michael已经被删除了。
  我们再使用命令删除最后一个别名:
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A1", "A2", [ "A3", "A4" ] ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$pop:{"ailas":1}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A1", "A2" ], "name" : "chenzhou" }
  6.>
  由结果可以看出,alias字段中最后一个别名["A3","A4"]被删除了。
  8.$pull
  用法:{$pull:{field:_value}}
  作用:从数组field内删除一个等于_value的值
  示例:删除chenzhou记录中的别名A1
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A1", "A2" ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$pull:{"ailas":"A1"}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A2" ], "name" : "chenzhou" }
  6.>
  9.$pullAll
  用法:{$pullAll:value_array}
  作用:用法同$pull一样,可以一次性删除数组内的多个值。
  示例: 删除chenzhou记录内的所有别名
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ "A1", "A2" ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$pullAll:{"ailas":["A1","A2"]}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ ], "name" : "chenzhou" }
  6.>
  可以看到A1和A2已经全部被删除了
  10.$rename
  用法:{$rename:{old_field_name:new_field_name}}
  作用:对字段进行重命名
  示例:把chenzhou记录的name字段重命名为sname
  Shell代码
  1.> db.students.find()
  2.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ ], "name" : "chenzhou" }
  3.> db.students.update({name:"chenzhou"},{$rename:{"name":"sname"}})
  4.> db.students.find()
  5.{ "_id" : ObjectId("5030f7ac721e16c4ab180cdb"), "ailas" : [ ], "sname" : "chenzhou" }
  6.>
  由结果可以看出name字段已经被更新为sname了。
  三.查询
  1.查询1条数据
  > db.cardpaybuydatas.findOne()
  2.条件查询
  db.orders.find({"recive_pid":28594661,createTime:{'$gte':1436025600,'$lt':1436112000}})
  一.MongoDb 命令查询所有数据库列表
  MongoDb 命令查询所有数据库列表
  CODE:
  > show dbs
  如果想查看当前连接在哪个数据库下面,可以直接输入db
  CODE:
  > db
  Admin
  想切换到test数据库下面
  CODE:
  > use test
  switched to db test
  > db
  Test
  想查看test下有哪些表或者叫collection,可以输入
  CODE:
  > show collections
  system.indexes
  user
  想知道mongodb支持哪些命令,可以直接输入help
  CODE:
  > help
  Dos代码
  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               set curent database to
  db.help()                  help on DB methods
  db.foo.help()                help on collection methods
  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
  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
  set curent database to
  db.help()
  help on DB methods
  db.foo.help()
  help on collection methods
  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
  如果想知道当前数据库支持哪些方法:
  CODE:
  > db.help();
  Java代码
  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, {>  db.currentOp() displays the current operation in the db
  db.dropDatabase()      删除当前数据库
  db.eval_r(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 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, {>  db.currentOp() displays the current operation in the db
  db.dropDatabase()      删除当前数据库
  db.eval_r(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
  如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:
  CODE:
  > db.user.help();user为表名
  Java代码
  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( , ) - first parameter is an optional query filter. second parameter is optional set of fields to return.
  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( , ) - first parameter is an optional query filter. second parameter is optional set of fields to return.
  根据条件查找数据
  -----------------------
  通过条件查询: 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() 根据条件查询只查询一条数据
  db.foo.getDB() get DB object associated with collection返回表所属的库
  db.foo.getIndexes() 显示表的所有索引
  db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组
  db.foo.mapReduce( mapFunction , reduceFunction ,)
  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() ->  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
  Mongodb的备份工具mongodump
  如果想备份数据库test 如:
  CODE:
  $ ./mongodump --help
  options:
  --help                   produce help message
  -h [ --host ] arg      mongo host to connect to
  -d [ --db ] arg          database to use
  -c [ --collection ] argcollection to use (some commands)
  -u [ --username ] arg    username
  -p [ --password ] arg    password
  --dbpath arg             directly access mongod data files in this path,
  instead of connecting to a mongod instance
  -v [ --verbose ]         be more verbose (include multiple times for more
  verbosity e.g. -vvvvv)
  -o [ --out ] arg (=dump) output directory
  $ ./mongodump -d test -o test/
  connected to: 127.0.0.1
  DATABASE: test         to         test/test
  test.user to test/test/user.bson
  100000 objects
  test.system.indexes to test/test/system.indexes.bson
  1 objects
  $ ls
  2   mongo   mongodump    mongofiles   mongorestoremongosniff
  dumpmongodmongoexportmongoimportmongos   test
  MongoDB的数据恢复工具mongorestore
  查看test库中的表
  CODE:
  > show collections
  system.indexes
  User
  删除user表
  CODE:
  > db.user.drop();
  True
  > show collections
  System.indexes
  现在利用mongorestore表恢复刚才利用mongodump备份的数据
  CODE:
  $ ./mongorestore --help
  usage: ./mongorestore
  options:
  --help                  produce help message
  -h [ --host ] arg       mongo host to connect to
  -d [ --db ] arg         database to use
  -c [ --collection ] arg collection to use (some commands)
  -u [ --username ] arg   username
  -p [ --password ] arg   password
  --dbpath arg            directly access mongod data files in this path,
  instead of connecting to a mongod instance
  -v [ --verbose ]      be more verbose (include multiple times for more
  verbosity e.g. -vvvvv)
  $ ./mongorestore -d test -c user test/test/user.bson
  connected to: 127.0.0.1
  test/test/user.bson
  going into namespace
  100000 objects
  User表中的10w条记录已经恢复
  CODE:
  > show collections
  system.indexes
  user
  > db.user.find();
  { "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" : "Falcon.C-1" }
  { "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" : "Falcon.C-2" }
  { "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" : "Falcon.C-3" }
  { "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" : "Falcon.C-4" }
  { "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" : "Falcon.C-5" }
  .................
  has more
  1. 超级用户相关:
  #增加或修改用户密码
  db.addUser('admin','pwd')
  #查看用户列表
  db.system.users.find()
  #用户认证
  db.auth('admin','pwd')
  #删除用户
  db.removeUser('mongodb')
  #查看所有用户
  show users
  #查看所有数据库
  show dbs
  #查看所有的collection
  show collections
  #查看各collection的状态
  db.printCollectionStats()
  #查看主从复制状态
  db.printReplicationInfo()
  #修复数据库
  db.repairDatabase()
  #设置记录profiling,0=off 1=slow 2=all
  db.setProfilingLevel(1)
  #查看profiling
  show profile
  #拷贝数据库
  db.copyDatabase('mail_addr','mail_addr_tmp')
  #删除collection
  db.mail_addr.drop()
  #删除当前的数据库
  db.dropDatabase()
  2. 客户端连接
  /usr/local/mongodb/bin/mongo user_addr -u user -p 'pwd'
  3. 增删改
  #存储嵌套的对象
  db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':})
  #存储数组对象
  db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
  #根据query条件修改,如果不存在则插入,允许修改多条记录
  db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
  #删除yy=5的记录
  db.foo.remove({'yy':5})
  #删除所有的记录
  db.foo.remove()
  4. 索引
  增加索引:1(ascending),-1(descending)
  db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
  #索引子对象
  db.user_addr.ensureIndex({'Al.Em': 1})
  #查看索引信息
  db.deliver_status.getIndexes()
  db.deliver_status.getIndexKeys()
  #根据索引名删除索引
  db.user_addr.dropIndex('Al.Em_1')
  5. 查询
  查找所有
  db.foo.find()
  #查找一条记录
  db.foo.findOne()
  #根据条件检索10条记录
  db.foo.find({'msg':'Hello 1'}).limit(10)
  #sort排序
  db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1})
  db.deliver_status.find().sort({'Ct':-1}).limit(1)
  #count操作
  db.user_addr.count()
  #distinct操作
  db.foo.distinct('msg')
  #>操作
  db.foo.find({"timestamp": {"$gte" : 2}})
  #子对象的查找
  db.foo.find({'address.city':'beijing'})
  6. 管理
  查看collection数据的大小
  db.deliver_status.dataSize()
  #查看colleciont状态
  db.deliver_status.stats()
  #查询所有索引的大小
  db.deliver_status.totalIndexSize()
  3.备份还原
  mongodb数据库同样离不开必要的维护,如备份、恢复、导入、导出。
  其实备份和恢复比导入和导出要方便些,而且一般不会出错,所以大部分时候使用备份和恢复操作就可以了
  1. 备份Mongodb
  mongodump    ip地址 -ddbname-o /home/user/mongdb_bak
  mongodump-hip地址:27017 -ddbname-o /home/user/mongdb_bak
  mongodump -htest.xxxx.com:52000 -d dataname -o /home/aa/dev/mongodb/data
  mongodump mongo导出数据库命令 mongodump –help 可以查看该命令下所有的帮助
  -h 导出源--host
  -d 要导出的数据库名称
  -o 数据库要导出的位置
  在终端滚过N行之后,数据库导出完成,可以去/home/aa/dev/mongodb/data目录下查看导出的文件,bson格式的(我导出后没有马上就看到文件,等了一会才出现的,原因不明)
  2. 恢复使用:mongorestore 命令
  mongorestore -d cmsdev /home/xx/dev/mongodb/data/cmsdev
  -d 使用的数据库名称
  后面直接加你刚才导出的目录,这样是直接恢复所有表
  如果-c 是恢复一个表
  3. 导入
  mongoimport -d my_mongodb -c user user.dat
  参数说明:
  -d 指明使用的库, 本例中为”my_mongodb”
  -c 指明要导出的表, 本例中为”user”
  可以看到导入数据的时候会隐式创建表结构
  4. 导出
  mongoexport -dmy_mongodb -c user -o user.dat
  参数说明:
  -d 指明使用的库, 本例中为”my_mongodb”
  -c 指明要导出的表, 本例中为”user”
  -o 指明要导出的文件名, 本例中为”user.dat”
  从上面可以看到导出的方式使用的是JSON 的样式
二.通过mongodump和mongorestore实现Mongodb备份和恢复
  博客分类:
  ·      Mongodb
  mongomongodbnosql备份恢复
  Mongodb自带了mongodump和mongorestore这两个工具来实现对数据的备份和恢复。
  mongodump能够在Mongodb运行时进行备份,它的工作原理是对运行的Mongodb做查询,然后将所有查到的文档写入磁盘。但是存在的问题时使用mongodump产生的备份不一定是数据库的实时快照,如果我们在备份时对数据库进行了写入操作,则备份出来的文件可能不完全和Mongodb实时数据相等。另外在备份时可能会对其它客户端性能产生不利的影响。
  mongodump用法如下:
  Shell代码http://blog.51cto.com/e/u261/themes/default/images/spacer.gif
  1. # ./bin/mongodump --help
  2. Export MongoDB data to BSON files.
  3.
  4. options:
  5.   --help                   produce help message
  6.   -v [ --verbose ]         be more verbose (include multiple times for more
  7.                            verbosity e.g. -vvvvv)
  8.   --version                print the program's version and exit
  9.   -h [ --host ] arg      mongo host to connect to ( /s1,s2 for
  10.                           sets)
  11.--port arg               server port. Can also use --host hostname:port
  12.--ipv6                   enable IPv6 support (disabled by default)
  13.-u [ --username ] arg    username
  14.-p [ --password ] arg    password
  15.--dbpath arg             directly access mongod database files in the given
  16.                           path, instead of connecting to a mongodserver -
  17.                           needs to lock the data directory, so cannot be used
  18.                           if a mongod is currently accessing the same path
  19.--directoryperdb         if dbpath specified, each db is in a separate
  20.                           directory
  21.--journal                enable journaling
  22.-d [ --db ] arg          database to use
  23.-c [ --collection ] argcollection to use (some commands)
  24.-o [ --out ] arg (=dump) output directory or "-" for stdout
  25.-q [ --query ] arg       json query
  26.--oplog                  Use oplog for point-in-time snapshotting
  27.--repair               try to recover a crashed database
  28.--forceTableScan         force a table scan (do not use $snapshot)
  参数说明:
  -h:指明数据库宿主机的IP
  -u:指明数据库的用户名
  -p:指明数据库的密码
  -d:指明数据库的名字
  -c:指明collection的名字
  -o:指明到要导出的文件名
  -q:指明导出数据的过滤条件
  具体使用示例如下:
  Shell代码
  1. # ./bin/mongodump -d test -o data/backup
  2. connected to: 127.0.0.1
  3. DATABASE: test   to   data/backup/test
  4.   test.system.indexes to data/backup/test/system.indexes.bson
  5.          9 objects
  6.   test.users to data/backup/test/users.bson
  7.          3 objects
  8.   test.games to data/backup/test/games.bson
  9.          1 objects
  10.    test.blog.post to data/backup/test/blog.post.bson
  11.         1 objects
  12.    test.lists to data/backup/test/lists.bson
  13.         1 objects
  14.    test.math to data/backup/test/math.bson
  15.         1 objects
  16.    test.map to data/backup/test/map.bson
  17.         8 objects
  18.    test.my_collection to data/backup/test/my_collection.bson
  19.         0 objects
  20.    test.foo to data/backup/test/foo.bson
  21.         6 objects
  22.    test.system.users to data/backup/test/system.users.bson
  23.         1 objects
  mongorestore是Mongodb从备份中恢复数据的工具,它主要用来获取mongodump的输出结果,并将备份的数据插入到运行的Mongodb中。
  mongorestore命令使用方法如下:
  Shell代码
  1. # ./bin/mongorestore --help
  2. usage: ./bin/mongorestore
  3. options:
  4.   --help                  produce help message
  5.   -v [ --verbose ]      be more verbose (include multiple times for more
  6.                           verbosity e.g. -vvvvv)
  7.   --version               print the program's version and exit
  8.   -h [ --host ] arg       mongo host to connect to ( /s1,s2 for sets)
  9.   --port arg            server port. Can also use --host hostname:port
  10.--ipv6                  enable IPv6 support (disabled by default)
  11.-u [ --username ] arg   username
  12.-p [ --password ] arg   password
  13.--dbpath arg            directly access mongod database files in the given
  14.                        path, instead of connecting to a mongodserver -
  15.                        needs to lock the data directory, so cannot be used
  16.                        if a mongod is currently accessing the same path
  17.--directoryperdb      if dbpath specified, each db is in a separate
  18.                        directory
  19.--journal               enable journaling
  20.-d [ --db ] arg         database to use
  21.-c [ --collection ] arg collection to use (some commands)
  22.--objcheck            validate object before inserting
  23.--filter arg            filter to apply before inserting
  24.--drop                  drop each collection before import
  25.--oplogReplay         replay oplog for point-in-time restore
  26.--keepIndexVersion      don't upgrade indexes to newest version
  参数说明:
  -h:指明数据库宿主机的IP
  -u:指明数据库的用户名
  -p:指明数据库的密码
  -d:指明数据库的名字
  -c:指明collection的名字
  -o:指明到要备份的文件名
  -q:指明备份数据的过滤条件
  具体使用示例如下:
  Shell代码
  1. # ./bin/mongorestore -d test --drop data/backup/test/
  2. connected to: 127.0.0.1
  3. Tue Aug 14 01:18:17 data/backup/test/games.bson
  4. Tue Aug 14 01:18:17      going into namespace
  5. Tue Aug 14 01:18:17      dropping
  6. 1 objects found
  7. Tue Aug 14 01:18:17 data/backup/test/foo.bson
  8. Tue Aug 14 01:18:17      going into namespace
  9. Tue Aug 14 01:18:17      dropping
  10.6 objects found
  11.Tue Aug 14 01:18:17 data/backup/test/blog.post.bson
  12.Tue Aug 14 01:18:17      going into namespace
  13.Tue Aug 14 01:18:17      dropping
  14.1 objects found
  15.Tue Aug 14 01:18:17 data/backup/test/lists.bson
  16.Tue Aug 14 01:18:17      going into namespace
  17.Tue Aug 14 01:18:17      dropping
  18.1 objects found
  19.Tue Aug 14 01:18:17 data/backup/test/map.bson
  20.Tue Aug 14 01:18:17      going into namespace
  21.Tue Aug 14 01:18:17      dropping
  22.8 objects found
  23.Tue Aug 14 01:18:17 data/backup/test/math.bson
  24.Tue Aug 14 01:18:17      going into namespace
  25.Tue Aug 14 01:18:17      dropping
  26.1 objects found
  27.Tue Aug 14 01:18:17 data/backup/test/system.users.bson
  28.Tue Aug 14 01:18:17      going into namespace
  29.1 objects found
  30.Tue Aug 14 01:18:17 data/backup/test/my_collection.bson
  31.Tue Aug 14 01:18:17      going into namespace
  32.Tue Aug 14 01:18:17      dropping
  33.Tue Aug 14 01:18:17 file data/backup/test/my_collection.bson empty, skipping
  34.Tue Aug 14 01:18:17 data/backup/test/users.bson
  35.Tue Aug 14 01:18:17      going into namespace
  36.Tue Aug 14 01:18:17      dropping
  37.3 objects found
  38.Tue Aug 14 01:18:17 data/backup/test/system.indexes.bson
  39.Tue Aug 14 01:18:17      going into namespace
  40.Tue Aug 14 01:18:17      dropping
  41.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.users", name: "_id_" }
  42.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.games", name: "_id_" }
  43.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.blog.post", name: "_id_" }
  44.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.lists", name: "_id_" }
  45.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.math", name: "_id_" }
  46.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.map", name: "_id_" }
  47.Tue Aug 14 01:18:17 { key: { gps: "2d" }, ns: "test.map", name: "gps_", min: -180.0, max: 181.0 }
  48.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.foo", name: "_id_" }
  49.Tue Aug 14 01:18:17 { key: { _id: 1 }, ns: "test.system.users", name: "_id_" }
  50.9 objects found
三.import
  http://www.iyunv.net/article/52498.htm
四.MongoDB条件操作符
描述
  条件操作符用于比较两个表达式并从mongoDB集合中获取数据。
  在本章节中,我们将讨论如何在MongoDB中使用条件操作符。
  MongoDB中条件操作符有:

[*]  (>) 大于 - $gt
[*]  (=) 大于等于 - $gte
[*]  () 大于操作符- $gt
  如果你想获取"testtable"集合中"age" 大于22的数据,你可以使用以下命令:
  >db.testtable.find({age: {$gt : 22}})
  类似于SQL语句:
  Select* from testtable where age >22;
MongoDB(>=)大于等于操作符- $gte
  如果你想获取"testtable"集合中"age" 大于等于22的数据,你可以执行以下命令:
  >db.testtable.find({age: {$gte : 22}})
  类似于SQL语句:
  Select * from testtablewhere age >=22;
MongoDB(
页: [1]
查看完整版本: mongodb 命令相关