Created
February 17, 2017 03:07
-
-
Save savokiss/46c6054cf24e2772d6c75115a4d36679 to your computer and use it in GitHub Desktop.
mongodb aggregate.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongo = require('mongodb').MongoClient; | |
var url = 'mongodb://localhost:27017/learnyoumongo'; | |
var size = process.argv[2]; | |
mongo.connect(url, function(err,db){ | |
if(err) throw err; | |
var prices = db.collection('prices'); | |
prices.aggregate([{ | |
$match: { | |
size: size | |
} | |
},{ | |
$group:{ | |
_id: 'avg', | |
avg:{ | |
$avg: '$price' | |
} | |
} | |
}]).toArray(function(err, results){ | |
if(err) throw err; | |
var o = results[0]; | |
console.log(Number(o.avg).toFixed(2)); | |
db.close(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment