forked from srushti1200/mongodb-aggregations-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregationPipeline.js
99 lines (89 loc) · 2.33 KB
/
aggregationPipeline.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const { MongoClient } = require("mongodb");
require('dotenv').config();
const url = process.env.MONGOURL;
const execPipeline = [
{
'$group': {
'_id': {
'userId': '$userId',
'name': '$name'
},
'totalBill': {
'$sum': '$currentBill'
},
'totalPending': {
'$sum': '$amountPending'
},
'totalPaid': {
'$sum': '$amountPaid'
},
'NumOrders': {
'$sum': 1
}
}
}, {
'$project': {
'_id': 1,
'NumOrders': 1,
'totalPaid': 1,
'totalBill': 1,
'status': {
'$cond': {
'if': {
'$gte': [
0, {
'$subtract': [
'$totalBill', '$totalPaid'
]
}
]
},
'then': 'paid',
'else': 'pending'
}
},
'pending': {
'$cond': {
'if': {
'$lt': [
0, {
'$subtract': [
'$totalBill', '$totalPaid'
]
}
]
},
'then': {
'$subtract': [
'$totalBill', '$totalPaid'
]
},
'else': '$$REMOVE'
}
}
}
}
]
async function main(){
const client = new MongoClient(url);
try{
await client.connect();
await getOrderSummary(client);
}
finally{
await client.close();
}
}
main().catch(console.error);
async function getOrderSummary(client){
const aggCursor = client.db("AggregationDB").collection("orders").aggregate(execPipeline);
await aggCursor.forEach(record =>{
if(record.status == 'pending'){
console.log(`name: ${record._id.name}\t status:${record.status} \t pending:${record.pending}`);
}
else{
console.log(`name: ${record._id.name}\t status:${record.status} `);
}
})
}
// module.exports = { main };