从数组中检索值,然后使用MongoDB将其存储在csv文件中 [英] Retrieve the values from array and store it in csv file using MongoDB

查看:90
本文介绍了从数组中检索值,然后使用MongoDB将其存储在csv文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是输入的json文件.使用MongoDB编写Java代码以进行迭代.

This is input json file. Javascript code is written to iterate using MongoDB.

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

JavaScript函数

Javascript function

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

我希望将输出写入5列的3行的csv文件中,每一列都包含此模式中的值

I want the output to be written to csv file in 3 rows with 5 columns, each column containing a value in this pattern

Id名称年龄计数RatingValue

Id name age count RatingValue

14约翰年龄3502 5

14 john age 3502 5

17史密斯23 232 5

17 smith 23 232 5

推荐答案

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

Change that final print(result); to the following:

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

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

Note: The first line is just for the column headers; the second line prints each employee result on a separate line.

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

Then call your script and direct the output to a CSV file like so:

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

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

Note: The --quiet arg suppresses the standard Mongo header output (shell version and initial database).

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

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:

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

这篇关于从数组中检索值,然后使用MongoDB将其存储在csv文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆