前言
在mongodb上通過.system.js的特殊系統(tǒng)集合宪迟,存儲(chǔ)一些MongoDB環(huán)境下支持的js函數(shù)羔巢,供重復(fù)使用; 核心是在執(zhí)行某些查詢語句時(shí)悍抑,返回值中的某些被base64編碼的字段無法正常查看,想通過一條語句就能輸出base64解碼后的字段記錄开呐。
注意
本例使用的mongodb版本是4.0.10烟勋,不同的版本使用差異較大规求,MongoDB8.0開始了,system.js 功能并不通用卵惦,且不同的版本間使用js函數(shù)使用時(shí)也有很大不同
- 可能存在性能問題阻肿,生產(chǎn)慎用
- 不要在js中寫業(yè)務(wù)邏輯
使用步驟
- 在mongodb中創(chuàng)建一個(gè)函數(shù)
將JavaScript函數(shù)存儲(chǔ)在數(shù)據(jù)庫中,插入兩個(gè)字段:- _id 字段包含函數(shù)名稱沮尿,在每個(gè)數(shù)據(jù)庫中都是唯一的
- value 字段保存函數(shù)的具體實(shí)現(xiàn)
以下示例以增加base64Decode函數(shù)為例:
db.system.js.insertOne({ _id: "base64Decode", value: function(encodedString) { var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; // Base64 編碼表 var output = ''; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; encodedString = encodedString.replace(/[^A-Za-z0-9\+\/\=]/g, ''); while (i < encodedString.length) { enc1 = keyStr.indexOf(encodedString.charAt(i++)); enc2 = keyStr.indexOf(encodedString.charAt(i++)); enc3 = keyStr.indexOf(encodedString.charAt(i++)); enc4 = keyStr.indexOf(encodedString.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } return output; }});
- 執(zhí)行成功后丛塌,會(huì)提示插入成功,否則會(huì)提示各種語法等的錯(cuò)誤畜疾,做調(diào)整重新插入即可
- 將存儲(chǔ)成功的函數(shù)加載到shell中赴邻,這個(gè)不會(huì)有返回值
db.loadServerScripts()
- 運(yùn)行已存儲(chǔ)的函數(shù)
> base64Decode("SGVsbG8gV29ybGQ=") Hello World
- 在查詢語句里使用,假設(shè)mongoDB的users表中有name和encodedField兩個(gè)字段啡捶,且encodedField字段是base64編碼后的字符串乍楚,查詢結(jié)果是encodedField的base64解碼后的字符串輸出。
> db.users.find({'encodedField': {$ne: null}, 'name': 'tomcat'}, {_id: 0, encodedField: 1}).forEach(function(doc){doc.encodedField = base64Decode(doc.encodedField); print(doc.encodedField);})
# 當(dāng)需要輸出整個(gè)document時(shí)届慈,可以把print() 改成printjson(doc),就會(huì)輸出完整的文檔信息json形式輸出
# ubuntu 環(huán)境下也可以通過 shell 命令 echo "SGVsbG8gV29ybGQ=" | base64 --decode 對(duì)單一進(jìn)行解碼
參考文檔:https://www.mongodb.com/zh-cn/docs/manual/tutorial/store-javascript-function-on-server/