问题描述
我在 32 位 Windows7 机器上使用 MongoDB 2.2.2.我在 .js 文件中有一个复杂的聚合查询.我需要在 shell 上执行这个文件并将输出定向到一个 CSV 文件.我确保查询返回一个平面"json(没有嵌套的键),所以它本质上可以转换为一个整洁的 csv.
我知道 load()
和 eval()
.eval()
要求我将整个查询粘贴到 shell 中,并且只允许 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 转换器工作(尽管 this 看起来很有希望).我最终做的是在我的 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);
});
我只是将查询通过管道传输到标准输出
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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!