Mongosh --eval:花括号与语法错误
bash 5.1.8
mongosh 2.5.10
mongodb 8.2.9
这就能工作:
$ mongosh HIFRRMGP --eval 'db.AuditLogCollection.countDocuments({})'
137
这也能工作:
$ mongosh HIFRRMGP --quiet
HIFRRMGP> db.AuditLogCollection.countDocuments({}, { hint: "_id_" })
137
但这不行:
$ mongosh HIFRRMGP --eval 'db.AuditLogCollection.countDocuments({}, { hint: "_id_" })'
SyntaxError: Unexpected token (1:40)
> 1 | db.AuditLogCollection.countDocuments({},
请注意单引号。我本来希望那样就能把大括号直接传给 mongosh。
我也试过 hint,但也失败了:
$ mongosh HIFRRMGP --eval 'db.AuditLogCollection.countDocuments({}).hint("_id_")'
TypeError: db.AuditLogCol ... ts({}).hint is not a function
解决方法是什么?
解决方案
行为怪异,我也看不出有什么理由会失败。下面给出一些替代方案,你可以尝试,在不需要创建额外文件的前提下:
mongosh HIFRRMGP --eval "db.AuditLogCollection.countDocuments({}, { hint: '_id_' })"
echo 'db.AuditLogCollection.countDocuments({}, { hint: "_id_" })' | mongosh HIFRRMGP
mongosh HIFRRMGP <<< 'db.AuditLogCollection.countDocuments({}, { hint: "_id_" })'
cmd='db.AuditLogCollection.countDocuments({}, { hint: "_id_" })'
mongosh HIFRRMGP --eval "$cmd"
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。