如何在Node.js程序中获取MongoDB服务器时间(非本地时间)?
获取MongoDB服务器时间(Node.js实现)
首先要明确:MongoDB使用的是**MongoDB查询语言(MQL)**而非SQL,以下是Node.js中获取MongoDB服务器时间的几种实用方法:
使用
db.adminCommand()命令
通过调用MongoDB的serverStatus命令提取服务器时间,这是最直接的方式:const { MongoClient } = require('mongodb'); async function getMongoServerTime() { const uri = 'mongodb://你的MongoDB连接地址'; const client = new MongoClient(uri); try { await client.connect(); const adminDb = client.db().admin(); const serverStatus = await adminDb.command({ serverStatus: 1 }); const serverTime = serverStatus.localTime; console.log('MongoDB服务器时间:', serverTime); return serverTime; } finally { await client.close(); } } getMongoServerTime();返回的
localTime即为MongoDB服务器所在时区的当前时间。使用
$currentDate聚合操作符
如果需要在聚合流程中获取服务器时间,可借助$currentDate操作符,无需依赖集合内的实际数据:async function getServerTimeViaAggregation() { const uri = 'mongodb://你的MongoDB连接地址'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('你的数据库名称'); const result = await db.collection('任意集合名称').aggregate([ { $project: { serverTime: { $currentDate: { $type: 'date' } } } }, { $limit: 1 } ]).toArray(); const serverTime = result[0]?.serverTime; console.log('MongoDB服务器时间:', serverTime); return serverTime; } finally { await client.close(); } } getServerTimeViaAggregation();废弃方法:
db.eval()
该方法在MongoDB 4.2及以上版本已被移除,仅作历史参考:// 不推荐使用,已废弃 async function getServerTimeDeprecated() { const uri = 'mongodb://你的MongoDB连接地址'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('你的数据库名称'); const serverTime = await db.eval('return new Date();'); console.log('MongoDB服务器时间:', serverTime); return serverTime; } finally { await client.close(); } }
内容的提问来源于stack exchange,提问作者dbwdbw1
相关产品推荐
相关产品推荐

