如何使用MongoDB在csv中存储数组的输出

时间:2014-10-10 19:28:59

标签: javascript mongodb csv

示例json数据文件

{
  "Includes": {
    "Employees": {
      "14": {
        "name": "john",
        "age": 12,
        "activity": {
          "Count": 3502,
          "RatingValue": 5
        }
      },
      "17": {
        "name": "smith",
        "age": 23,
        "activity": {
          "Count": 232,
          "RatingValue": 5
        }
      }
    }
  }
}

编写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);

我们如何在csv中存储2行数组的输出,因为数据包含2行,使用mongoexport。在csv中输出必须是

14,约翰,12,3502,5

17,史密斯,23,232,5

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

将最终print(result);更改为以下内容:

print(result.join("\n"));

然后调用您的脚本并将输出定向到CSV文件,如下所示:

mongo --quiet "full-path-to-script.js" > "full-path-to-output.csv"

注意:--quiet arg会抑制标准的Mongo标头输出(shell版本和初始数据库)。

我创建了详细信息集合,并将JSON文档添加到其中,然后运行修改后的脚本导致以下CSV文件内容:

14,john,12,3502,5
17,smith,23,232,5

如果您还想要一个CSV标题行,请在此处查看我几乎完全相同的答案:https://stackoverflow.com/a/26310323/3212415