Redirect output of mongo query to a csv file

后端 未结 7 752
隐瞒了意图╮
隐瞒了意图╮ 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:51

    Extending other answers:

    I found @GEverding's answer most flexible. It also works with aggregation:

    test_db.js

    print("name,email");
    
    db.users.aggregate([
        { $match: {} }
    ]).forEach(function(user) {
            print(user.name+","+user.email);
        }
    });
    

    Execute the following command to export results:

    mongo test_db < ./test_db.js >> ./test_db.csv
    

    Unfortunately, it adds additional text to the CSV file which requires processing the file before we can use it:

    MongoDB shell version: 3.2.10 
    connecting to: test_db
    

    But we can make mongo shell stop spitting out those comments and only print what we have asked for by passing the --quiet flag

    mongo --quiet test_db < ./test_db.js >> ./test_db.csv
    
    0 讨论(0)
提交回复
热议问题