-
Notifications
You must be signed in to change notification settings - Fork 0
/
export-aggregateToCSV.js
59 lines (47 loc) · 1.55 KB
/
export-aggregateToCSV.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// to connect: mongo "mongodb://mongo.example.com:27017/" "C:\Path\To\Script\export-aggregateToCSV.js" > "C:\Export\To\Path\out.csv"
var database = "";
var collection = "";
var pipeline = [];
var x = db.getSiblingDB(database).getCollection(collection).aggregate(pipeline, {allowDiskUse: true}).toArray();
toCSV(x, ";", false);
function toCSV(jsonArray, separator, fixedProjection) {
var headers = {};
var matrix = [[]];
if (!separator) separator = ";";
for (var i = 0; i < jsonArray.length; i++) {
matrix.push([]);
}
// search keys
try {
jsonArray.forEach(function(item) {
Object.keys(item).forEach(function(k) {
headers[k] = headers[k];
})
if (fixedProjection) {
throw new Error("No more forEach requiried.");
}
});
} catch (e) {
print("Warning: {fixedProjection: true}")
}
var matrixIndex = 1;
Object.keys(headers).forEach(function(k) {
matrix[0].push(k);
jsonArray.forEach(function(item) {
var result = null;
if (item[k]) {
result = item[k];
}
matrix[matrixIndex++].push(result);
})
matrixIndex = 1;
});
var line = "";
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
line += matrix[i][j] + ((j === matrix[i].length -1) ? "" : separator);
}
print(line);
line = "";
}
}