从数组中检索值,并使用MongoDB将其存储在csv文件中

Retrieve the values from array and store it in csv file using MongoDB

本文关键字:存储 csv 文件 MongoDB 检索 数组      更新时间:2023-09-26

这是一个输入json文件。编写Javascript代码是为了使用MongoDB进行迭代。

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

Javascript函数

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文件,分为3行,共5列,每列包含一个值,此模式为

Id名称年龄计数评分值

14约翰年龄3502 5

17史密斯23 232 5

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

print("Id,name,age,count,RatingValue");
print(result.join("'n"));

注意:第一行仅用于列标题;第二行将每个员工的结果打印在单独的一行上。

然后调用脚本并将输出引导到CSV文件,如下所示:

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

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

我创建了一个details集合,并将您的JSON文档添加到其中,然后运行修改后的脚本,得到以下CSV文件内容:

Id,name,age,count,RatingValue
14,john,12,3502,5
17,smith,23,232,5