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
發佈了54 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章