許多開發者可能忽略了 MongoDB 原生支援 JavaScript 執行的特性,這在編寫定時腳本、定期檢查資料庫狀態或執行管理任務時極為實用。本文將詳細介紹在 MongoDB 環境中運行 JavaScript 的三種主要方式。
MongoDB 的互動式 Shell (mongo shell) 內建 JavaScript 引擎,允許直接輸入並執行 JS 代碼。以下示範日期物件的操作差異:
> new Date()
ISODate("2013-12-12T07:37:00.074Z")
> x = new Date();
ISODate("2013-12-12T07:37:05.724Z")
> x.getTime();
1386833825724
> var y = Date();
> y.getTime()
Thu Dec 12 15:37:26.805 TypeError: Object Thu Dec 12 2013 15:37:21 GMT+0800 (CST) has no method 'getTime'
>
new Date() vs Date()new Date():回傳 Date 物件,可呼叫 getTime() 取得自 Unix 紀元以來的毫秒數。Date():僅為函式,回傳字串格式的日期時間,不具備 getTime() 方法,易造成誤用。參考資源:StackOverflow 討論串
$where 運算子$where 運算子允許在查詢條件中執行 JavaScript 函式,實現複雜的邏輯判斷。例如:找出「最後活動時間超過 300 秒」且「狀態為 offline」的文件:
db.display.find({
$and: [
{$where: function() {
return new Date().getTime() / 1000 - this.last_active_time > 300
}},
{status: "offline"}
]
})
官方文件參考:$where 運算子文件
效能提醒:$where 會逐文件評估 JavaScript,效能較一般查詢運算子低,建議僅在必要時使用,並配合索引欄位縮小掃描範圍。
適用於自動化維護任務。將查詢與輸出邏輯寫入檔案 (如 test.js):
cursor = db.display.find({
$and: [
{$where: function() {
return new Date().getTime() / 1000 - this.last_active_time > 300
}},
{status: "offline"}
]
});
while (cursor.hasNext()) {
printjson(cursor.next());
}
執行指令:
mongo localhost/mydb test.js
此方式便於納入排程任務 (cron job / Windows 排程器),實現資料庫的自動化巡檢與報表產出。
善用 MongoDB 的 JavaScript 執行能力,能大幅提升資料庫管理自動化程度。從互動式 Shell 的即時除錯、$where 的複雜條件查詢,到外部腳本檔案的排程執行,三種方式各有適用場景。實務上建議優先使用原生查詢運算子,僅在邏輯無法用聲明式語法表達時,才引入 JavaScript。