将mongo查询的输出重定向到csv文件 [英] Redirect output of mongo query to a csv file
问题描述
我将MongoDB 2.2.2用于32位Windows7计算机.我在.js文件中有一个复杂的聚合查询.我需要在外壳上执行此文件,并将输出定向到CSV文件.我确保查询返回的是平面" json(无嵌套键),因此它本质上可以转换为纯净的csv.
我知道load()
和eval()
. eval()
要求我将整个查询粘贴到外壳中,并且在脚本中只允许printjson()
,而我需要csv.第二种方法:load()
..它将输出显示在屏幕上,并再次以json格式输出.
Mongo有没有办法从json转换为csv? (我需要csv文件来准备关于数据的图表).我在想:
1.这两个mongo都有一个内置命令,我现在找不到.
2. Mongo不能为我做;我最多可以将json输出发送到一个文件,然后自己将其转换为csv.
3. Mongo可以将json输出发送到一个临时集合,其内容可以很容易地mongoexported
转换为csv格式.但是我认为只有map-reduce查询支持输出集合.是对的吗?汇总查询需要它.
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 CSV file. I ensure that the query returns a "flat" json (no nested keys), so it is inherently convertible to a neat csv.
I know about load()
and eval()
. eval()
requires me to paste the whole query into the shell and allows only printjson()
inside the script, while I need csv. And, the second way: load()
..It prints the output on the screen, and again in json format.
Is there a way Mongo can do this conversion from json to csv? (I need csv file to prepare charts on the data). I am thinking:
1. Either mongo has a built-in command for this that I can't find right now.
2. Mongo can't do it for me; I can at most send the json output to a file which I then need to convert to csv myself.
3. Mongo can send the json output to a temporary collection, the contents of which can be easily mongoexported
to csv format. But I think only map-reduce queries support output collections. Is that right? I need it for an aggregation query.
感谢您的帮助:)
推荐答案
我知道这个问题很旧,但是我花了一个小时试图将一个复杂的查询导出到csv,我想分享自己的想法.首先,我无法使用任何json到csv转换器(尽管这看起来很有希望).我最终要做的是在mongo脚本中手动编写csv文件.
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);
});
这只是我将查询通过管道发送到stdout
This I just piped the query to stdout
mongo test export.js > out.csv
其中test
是我使用的数据库的名称.
where test
is the name of the database I use.
这篇关于将mongo查询的输出重定向到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!