Redirect output of mongo query to a csv file

后端 未结 7 808
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 06:01

I am using MongoDB 2.2.2 for 32-bit Windows7 machine. I have a complex aggregation query in a .js file. I need to execute this file on the shell and direct the output to a C

7条回答
  •  攒了一身酷
    2020-12-02 06:37

    Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.

    cursor = db..;
    
    headerPrinted = false;
    while (cursor.hasNext()) {
        item = cursor.next();
        
        if (!headerPrinted) {
            print(Object.keys(item).join(','));
            headerPrinted = true;
        }
    
        line = Object
            .keys(item)
            .map(function(prop) {
                return '"' + item[prop] + '"';
            })
            .join(',');
        print(line);
    }
    

    Save this as a .js file, in this case we'll call it example.js and run it with the mongo command line like so:

    mongo  example.js --quiet > example.csv
    

提交回复
热议问题