开发者

mongo dbname --eval 'db.collection.find()' does not work

Why does this work:

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

While this does not work:

# mongo localhost/dbname --eval 'db.collection.find()'
MongoDB she开发者_运维问答ll version: 1.8.3
connecting to: localhost/dbname
DBQuery: dbname.collection -> undefined

It should be exactly the same, no?

Thanks!


The return val of db.collection.find() is a cursor type. Executing this command from within the shell will create a cursor and show you the first page of data. You can start going through the rest by repeating the 'it' command.

I think the scope of variables used during the execution of an eval'd script is only for the lifetime of the script (data can be persisted into collections of course) so once the script terminates those cursor variables no longer exist and so you would be able to send another eval script to page the data. So the behaviour you get during a shell session wouldn't really work from an eval script.

To get close to the behaviour you could run something like this:

mongo dbname --eval "db.collection.find().forEach(printjson)"

That shows you that the command does execute and produce a cursor which you can then iterate over sending the output to stdout.

Edit: I think the point I was trying to make was that the command you are issuing is working its just the output is not what you expect.


The printjson functions covers a lot of ground when scripting with mongo --eval '...'. Rather than chaining .forEach you can simply wrap your call.

$ mongo --eval 'db.stats_data.stats()' db_name
MongoDB shell version: 2.4.14
connecting to: db_name
[object Object]

$ mongo --eval 'db.stats_data.stats().forEach(printjson)' db_name
MongoDB shell version: 2.4.14
connecting to: db_name
Tue Jan 10 15:32:11.961 TypeError: Object [object Object] has no method 'forEach'

$ mongo --eval 'printjson(db.stats_data.stats())' db_name
MongoDB shell version: 2.4.14
connecting to: db_name
{
    "ns" : "db_name.stats_data",
    "count" : 5516290,
    "size" : 789938800,
    "avgObjSize" : 143.20110073980882,
    "storageSize" : 1164914688,
    "numExtents" : 18,
    "nindexes" : 3,
    "lastExtentSize" : 307515392,
    "paddingFactor" : 1.0000000000000457,
    "systemFlags" : 1,
    "userFlags" : 0,
    "totalIndexSize" : 1441559616,
    "indexSizes" : {
        "_id_" : 185292688,
        "owner_id_key_idx" : 427678384,
        "onwer_metric_key_idx" : 828588544
    },
    "ok" : 1
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜