0

I have something like below in my mongo js file

db.eval(function(){
   db.user.find( { email : {$exists : false}} ).forEach(
     function(found){
            id = found._id; 
            print(id);  // this will print to mongo logs

print() will print to mongodb logs but I want to send these ids found to an output.txt file in some other location . Because I need to email this file for further processing. Is it possible ? Thanks..

NewQueries
  • 4,841
  • 11
  • 33
  • 39
  • don't use db.eval() use the shell and redirect its output to a file. See http://stackoverflow.com/questions/13104800/printing-mongodb-shell-output-to-file/13111118#13111118 – Asya Kamsky Nov 14 '13 at 01:01

1 Answers1

0

You can use mongoexport from command line.

Example:

mongoexport -d mydatabase                   \
    --fields _id                            \
    --query '{ email: { $exists: false }}'  \
    -c user                                 \
    --csv                                   \
    --out myfile_for_further_processing.csv

For more options have a look at the docs.

Edit Oh, I haven't noticed you use mongojs. This you can do another way:

var fs = require('fs');

db.user.find( { email : {$exists : false}}, function (err, docs) {
    if (err) throw err;

    var ids = docs.map(function (doc) {
        return doc._id.toHexString();
    });

    // I assume it is not critical when using sync-version
    fs.writeFileSync('output.txt', ids.join('\n'), 'utf8');
});

(There might be many errors in the code, I just wrote the text w/o editor/test.)

hgoebl
  • 12,637
  • 9
  • 49
  • 72