mongo dbname --eval'db.collection.find()'不起作用

cha*_*lax 20 mongodb

为什么这样做:

# mongo dbname
MongoDB shell version: 1.8.3
connecting to: nextmuni_staging
> db.collection.find()
{ "foo" : "bar" }
> bye
Run Code Online (Sandbox Code Playgroud)

虽然这不起作用:

# mongo localhost/dbname --eval 'db.collection.find()'
MongoDB shell version: 1.8.3
connecting to: localhost/dbname
DBQuery: dbname.collection -> undefined
Run Code Online (Sandbox Code Playgroud)

应该完全相同,不是吗?

谢谢!

JB.*_*JB. 24

返回值db.collection.find()是游标类型.从shell中执行此命令将创建一个游标并显示第一页数据.您可以通过重复'it'命令开始完成剩下的工作.

我认为在执行eval'd脚本期间使用的变量范围仅适用于脚本的生命周期(数据当然可以保存到集合中),因此一旦脚本终止这些游标变量就不再存在,所以你会能够发送另一个eval脚本来分页数据.因此,在shell会话期间获得的行为无法通过eval脚本真正起作用.

要接近行为,您可以运行以下内容:

mongo dbname --eval "db.collection.find().forEach(printjson)"
Run Code Online (Sandbox Code Playgroud)

这表明命令执行并生成一个游标,然后您可以迭代将输出发送到stdout.

编辑:我认为我试图提出的一点是,你发出的命令正在运行它的输出并不是你所期望的.