Is there a way to echo the output of the mongo shell to a file?

20,342 views
Skip to first unread message

thetuxracer

unread,
Mar 19, 2011, 10:00:26 AM3/19/11
to mongod...@googlegroups.com
The files that mongoexport creates are unreadable. Is there a way/hack to export the output of a command executed on the mongodb shell to a file?

Thanks.

Scott Hernandez

unread,
Mar 19, 2011, 10:10:57 AM3/19/11
to mongod...@googlegroups.com
You can simply pipe it out.

mongo dbname file.js >> out.txt

> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.
>

thetuxracer

unread,
Mar 22, 2011, 7:34:32 AM3/22/11
to mongod...@googlegroups.com, Scott Hernandez
I do not get the output of the command. I only get this:

MongoDB shell version: 1.8.0
connecting to: foo

Scott Hernandez

unread,
Mar 22, 2011, 7:52:15 AM3/22/11
to mongod...@googlegroups.com
What is your script?

You may want to look at this page for more information:
http://www.mongodb.org/display/DOCS/Scripting+the+shell

heu...@yahoo.com.br

unread,
Jan 2, 2014, 5:41:12 PM1/2/14
to mongod...@googlegroups.com
Hi Scott.

I have readonly access to an specific database, so I´m only allowed to log on the server in a specific database.

I´,m running a query which is returning a large amount of results, and I need to export all of the results into an external file, can you help me?

I´ve already searched on how to write the javascript function file on this link, but I keep getting 

MongoDB shell version: 2.4.8
connecting to: test

my script is the following:

conn = new Mongo("server:port");
db = conn.getDB("collection_name");
db.auth('username','pass');

 var agg = [
    {$group: {
      _id: "$groupingfield",
      total: {$sum: 1}
    }}
  ];  
 
 db.collection.aggregate(agg);

and this is how I´m running it on shell:
C:\mongoDb\bin> mongo teste.js> output.txt


The teste.js file is at the bin directory, but it doesn´t seems to do anything.

Is there any mistake in what I´ve sent you? Can you send me the steps to do it?

Thanks man 

William Zola

unread,
Jan 4, 2014, 1:07:48 AM1/4/14
to mongod...@googlegroups.com
The 'mongo.exe' shell, by default, doesn't print out anything when running a script file.  This behavior is different than when run interactively.

You need to change the final line to read:

 printjson( db.collection.aggregate(agg) );


 -William
Reply all
Reply to author
Forward
0 new messages