1. 程式人生 > 實用技巧 >MongoDB基於時間戳的導數操作

MongoDB基於時間戳的導數操作

上班有個需求,協助提取某資料系統中cashloanDb

涉及MongoDB集合: cardBill(時間段 6.1-8.28) , cardReport (時間段 2.1-8.28)
如果不支援根據時間提取,可提取全量資料。
使用mongo客戶端命令進入資料庫:
jsfkrs0:PRIMARY> show dbs;
2018-09-04T17:35:57.692+0800 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",

"code" : 13,
"codeName" : "Unauthorized"
} :br/>[email protected]/mongo/shell/utils.js:25:13
[email protected]/mongo/shell/mongo.js:62:1
br/>[email protected]/mongo/shell/utils.js:769:19
[email protected]/mongo/shell/utils.js:659:15
br/>@(shellhelp2):1:1
這個是因為開啟conf檔案中的auth功能,設定使用者和密碼之後,再執行show dbs就會報錯,下面我們用db.auth()認證之後就可以執行了:
jsfkrs0:PRIMARY> use admin
switched to db admin
jsfkrs0:PRIMARY> db.auth('mangoadmin','password')
1
jsfkrs0:PRIMARY> show dbs;
admin 0.000GB
cashloanDb 96.287GB
fuf_mgdb 0.765GB
local 1.280GB

切換至我們要操作的db中
jsfkrs0:PRIMARY> use cashloanDb
switched to db cashloanDb

看一下這兩個集合的全量資料有多少
jsfkrs0:PRIMARY> db.cardBill.count();

247126
jsfkrs0:PRIMARY> db.cardReport.count();
249128

先看一下這個表裡面有沒有時間戳我們取一條資料來看,有的話,我們可以基於這個時間戳來進行匯出工作;
jsfkrs0:PRIMARY> db.cardBill.findOne();
{
"_id" : ObjectId("59e180110cxxxxxx"),
"timestamp" : NumberLong("1507950609625"),
"taskId" : "xxxxxx-b08d-11e7-bf17-xxxxx",
"bill" : "[{\"balance\":47000.00,\"deposits\":[],\"bills\":[{\"installments\":[],\"bill_id\":\"d81f1e60-a02d-11e7-a63a-00163e0dfac7\",\"bill_type\":\"DONE\",\"bank_name\":\"中信銀行\",\"bill_month\":\"2017-04\",\"bill_date\":\"2017-04-14\",\"payment_due

這個時間戳有13位,精確到了毫秒,我們在匯出的時候需要換算成Unix時間戳,並且也精確到毫秒才可以。
http://tool.chinaz.com/Tools/unixtime.aspx
MongoDB基於時間戳的導數操作

正常換算出來的只到秒位,只有10位。可以直接在換算出的Unix時間戳後面加000,或者換算的時候直接精確到毫秒,下來我們就可以用MangoDB自帶的匯出工具進行匯出;
mongoexport -d cashloanDb -c cardBill-uadmin -ppassword --authenticationDatabase "admin" -q '{"timestamp":{$gte:NumberLong("1517414400000"),$lte:NumberLong("1535472000000")}}' -o cardBill.json

轉載於:https://blog.51cto.com/yangjunfeng/2170461