2

Right now, I'm using mongodump and bsondump to get documents out of MongoDB, then applying regexes to the documents to get the value I want. What I really want is just a flat file of, say, the email address of every user in the users collection, in a flat file that I can then manipulate with grep, uniq, etc.

In MySQL, it'd be:

mysql < query.sql > outfile.txt

The query.sql file would be something like:

SELECT email FROM users;

But in Mongo, when I pass a .js file in, I'm still not sure how to make it output single values.

mongo --db test < query.js > outfile.txt

What would query.js be for the users collection?

Rich Armstrong
  • 1,432
  • 2
  • 16
  • 20
  • This question has been answered repeated [here][1] [1]: http://stackoverflow.com/questions/12823990/how-to-get-mongo-command-results-in-to-a-flat-file – user3404455 Apr 09 '14 at 00:55
  • Does this answer your question? [How to get mongo command results in to a flat file](https://stackoverflow.com/questions/12823990/how-to-get-mongo-command-results-in-to-a-flat-file) – Spevacus Jun 09 '22 at 16:09

2 Answers2

1

You could use forEach to run each result through a JavaScript function and print a line in the format you want:

db.users.find().forEach(function(user) {
    print(user.email);
});

The --quiet command line option is also useful for removing the header lines from the output.

Martin Owen
  • 5,221
  • 3
  • 35
  • 31
0

This question has been answered repeated here

in summary

mongo 127.0.0.1/db --eval "var c = db.collection.find(); while(c.hasNext()) 
{printjson(c.next())}" >> test.txt
Community
  • 1
  • 1
user3404455
  • 420
  • 1
  • 3
  • 9