You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

远程MongoDB集群统计错误日志报logs未定义错误如何解决?

问题根因

报错的核心是Shell单引号嵌套规则冲突:Shell 单引号包裹的字符串内部无法直接识别单引号,你写的'db.getCollection('logs').count(...)'会被Shell拆分为三段拼接:

  1. 第一段字符串:db.getCollection(
  2. Shell上下文的裸字符串:logs
  3. 第二段字符串:).count(...)
    传递到Mongo Shell后,logs会被识别为未声明的JS变量,因此抛出ReferenceError: logs is not defined。

解决方案

方案1(更推荐):直接使用--eval参数传递查询

无需通过管道传递内容,直接通过--eval传入查询语句,注意转义特殊字符即可,可运行命令如下:

mongo --ssl \
--sslPEMKeyFile /mongodb/certificate/test.pem \
--sslCAFile /mongodb/certificate/testCA.pem \
--authenticationDatabase '$external' \
--authenticationMechanism MONGODB-X509 \
--host MyServer.MyDomain \
--quiet \
--port 27019 \
--eval "db.getCollection('logs').count({\"timestamp\" : {\$gte: new Date(ISODate().getTime() - 1000 * 60 * 60 * 1)},\"level\" : \"error\",\"message\" : {\$not: {\$regex:  \".*sso\"}}})"

方案2:修正管道写法的引号转义

如果要保留管道写法,只需将内部的单引号替换为Shell单引号内嵌套单引号的标准写法'\''即可,可运行命令如下:

echo 'db.getCollection('\''logs'\'').count({"timestamp" : {$gte: new Date(ISODate().getTime() - 1000 * 60 * 60 * 1)},"level" : "error","message" : {$not: {$regex:  ".*sso"}}})' | mongo --ssl --sslPEMKeyFile /mongodb/certificate/test.pem --sslCAFile /mongodb/certificate/testCA.pem  --authenticationDatabase '$external' --authenticationMechanism MONGODB-X509 --host MyServer.MyDomain --quiet --port 27019

内容的提问来源于stack exchange,提问作者edwio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:39:01