-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregate.js
42 lines (33 loc) · 825 Bytes
/
aggregate.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
/*
output the average price
of the items that match
the size criteria input
the average is converted
to number and rounded to
2 decimals
*/
var mongoClient = require('mongodb').MongoClient;
var collectionName = 'prices';
var databaseName = 'learnyoumongo';
var size = process.argv[2];
var url = 'mongodb://localhost:27017/learnyoumongo';
mongoClient.connect(url, function(err, DB) {
var dataBase = DB.db(databaseName);
dataBase.collection(collectionName)
.aggregate([
{ $match: { size: size } },
{ $group: {
_id: 'average',
total: { $avg: '$price' }
} }
]).toArray(function(err, results) {
if (err) {
console.log(err);
}
if (!results.length) {
throw new Error('No results found')
}
console.log(Number(results[0].total).toFixed(2));
});
DB.close();
});