Skip to content

Instantly share code, notes, and snippets.

@savokiss
Created February 17, 2017 03:07
Show Gist options
  • Save savokiss/46c6054cf24e2772d6c75115a4d36679 to your computer and use it in GitHub Desktop.
Save savokiss/46c6054cf24e2772d6c75115a4d36679 to your computer and use it in GitHub Desktop.
mongodb aggregate.js
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