mongodb备份还原单表

mongodb备份整个数据库
mongodump -h 192.168.10.111--port 27017 -u username -p passwd -d wechat -o wechat

还原这个数据库
 mongorestore --host 192.168.10.111 -u username -p password --authenticationDatabase admin -d wechat --dir=/home/server/backup/mongodb/wechat

若是要删除本来的库再还原

 mongorestore --host 192.168.10.111 -u username -p password --authenticationDatabase admin -d wechat --dir=/home/server/backup/mongodb/wechat --drop














mongo备份单个表

mongoexport  --host 10.9.0.1 --port 27017 -u mongobf -p 03a4b868ff -d wechat -c article -o  article


根据时间段备份表
mongo时间戳转换
date -d 2016-06-10 +%s 或date -d "2016-06-10 00:00:00" +%s //输出:1465488000


date -d @1465488000 //输出:2016年 06月 10日 星期五 00:00:00 CST


db.article.find({"lastpopTime":{"$gte":1465488000}}).count()  //统计2016-06-10以后的数据

查询某个时间段的数据
db.article.find({"lastpopTime":{"$gte":1465488000,"lt":1470466800}}).count()


备份wechat数据库article表中2016-06-10以后的数据
mongodump --host 10.9.0.1 --port 27017 -u username -p userpasswd -d wechat -c article -q '{"lastpopTime":{"$gte":1465488000}}' -o 6-10

还原数据库中某个表
mongorestore -d wechat -c media   6-10/wechat/article.bson --drop  //还原bson格式数据

增量某个表的数据:
mongorestore -d wechat -c article   8-6/wechat/article.bson







经过Objectid备份数据
方法一:
mongodb shell中执行如下函数
function objectIdWithTimestamp(timestamp) {

   if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
   }

   var hexSeconds = Math.floor(timestamp/1000).toString(16);
  
   var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
   return constructedObjectId
}
查询2016/08/01号以后新入库的数据,或objectIdWithTimestamp('2016/08/01 00:00:00')
调用上面的函数:objectIdWithTimestamp转换成时间戳
db.collectionName.find({_id:{$gte:objectIdWithTimestamp('2016/08/01')}})
collectionName为集合名
如查询article集合中2016/08/01号以后新入库的数据
db.article.find({_id:{$gte:objectIdWithTimestamp('2016/08/01')}})
输出Objectid
objectIdWithTimestamp('2016/08/01')或
print(objectIdWithTimestamp('2016/08/01'))

使用Objectid备份数据
mongodump --host 10.9.0.1 --port 27017 -u username -p userpasswd -d wechat -c article -q '{"_id":{"$gte":ObjectId("579e20800000000000000000")}' -o 8-01

方法二:
objectid前4个字节表示数据入库的时间,即前8位。前4个字节为16进制数
咱们要查询2016-08-01号新入库的数据
首先:把日期变成时间戳
#date -d "2016-08-01" +%s
1469980800
而后:把时间戳变成16进制
#echo 'obase=16;ibase=10;1469980800'|bc
579E2080   //这个就是objectid的前8位了,在后面添上000000 0000 000000即为obiectid
ObjectId("579e20800000000000000000")

16进制转10进制
#echo $((0x579E2080))
1469980800