Redirect output of mongo query to a csv file

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

    I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script.

    This is a simple version but essentially what I did:

    print("name,id,email");
    db.User.find().forEach(function(user){
      print(user.name+","+user._id.valueOf()+","+user.email);
    });
    

    This I just piped the query to stdout

    mongo test export.js > out.csv
    

    where test is the name of the database I use.

提交回复
热议问题