[英]How to store output of array in csv using MongoDB
sample json data file 样本json数据文件
{
"Includes": {
"Employees": {
"14": {
"name": "john",
"age": 12,
"activity": {
"Count": 3502,
"RatingValue": 5
}
},
"17": {
"name": "smith",
"age": 23,
"activity": {
"Count": 232,
"RatingValue": 5
}
}
}
}
}
js was written to retrieve the nested document and stored in array 编写js来检索嵌套文档并存储在数组中
var result = [];
db.details.find().forEach(function(doc) {
var Employees = doc.Includes.Employees;
if (Employees) {
for (var key in Employees) {
var Employee = Employees[key];
var item = [];
item.push(key);
item.push(Employee.name);
item.push(Employee.age);
item.push(Employee.activity.Count);
item.push(Employee.activity.RatingValue);
result.push(item.join(","));
}
}
});
print(result);
How can we store the output of array in csv with 2 rows because the data contains 2 rows by using mongoexport. 我们如何使用2行将数组的输出存储在csv中,因为使用mongoexport数据包含2行。 In csv output must be
在CSV输出必须
14,john,12,3502,5 14,约翰,12,3502,5
17,smith,23,232,5 17,史密斯,23,232,5
var csv=""; //this is the output file
for(var i=0;i<result.length;i++){//loop through output
csv+=result[i]+"\n"; //append the text and a newline
}
window.open('data:text/csv;' + (window.btoa?'base64,'+btoa(csv):csv)); //open in a new window, chrome will automatically download since it is a csv.
Change that final print(result);
更改最终
print(result);
to the following: 到以下内容:
print(result.join("\n"));
Then call your script and direct the output to a CSV file like so: 然后调用您的脚本并将输出定向到CSV文件,如下所示:
mongo --quiet "full-path-to-script.js" > "full-path-to-output.csv"
Note: The --quiet
arg suppresses the standard Mongo header output (shell version and initial database). 注意:--
--quiet
arg禁止标准Mongo标头输出(shell版本和初始数据库)。
I created a details collection, and added your JSON document to it, and then running the modified script resulted in the following CSV file content: 我创建了一个详细信息集合,并向其中添加了您的JSON文档,然后运行修改后的脚本会产生以下CSV文件内容:
14,john,12,3502,5
17,smith,23,232,5
If you want a CSV header row as well, see my nearly identical answer to your nearly identical question here: https://stackoverflow.com/a/26310323/3212415 如果您还想要CSV标头行,请在此处查看我对几乎相同的问题的几乎相同的答案: https : //stackoverflow.com/a/26310323/3212415
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.