Ive coded out a simple query of $sum but it doesnt seem to be showing me the output i want. It is supposed to show the average air_temperature for all the machine_unit.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('meibanlist', ['meibanlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/meibanlist', function (req, res) {
console.log('I received a GET request');
db.meibanlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/meibanlist', function (req, res) {
console.log(req.body);
db.meibanlist.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/meibanlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.meibanlist.remove({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
});
});
app.get('/meibanlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.meibanlist.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
});
});
app.put('/meibanlist/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.machine_unit);
db.meibanlist.findAndModify({
query: {_id: mongojs.ObjectId(id)},
update: {$set: {machine_unit: req.body.machine_unit, air_temperature: req.body.air_temperature, water_temperature: req.body.water_temperature, heat_temperature: req.body.heat_temperature, room_temperature: req.body.room_temperature, date: req.body.date, time: req.body.time}},
new: true}, function (err, doc) {
res.json(doc);
}
);
});
///this is where it all went wrong
db.meibanlist.aggregate([{$project:{ "Average": { $avg: ["$air_temperature"] }}}], function(err, meibanlist){
if (err || !meibanlist) console.log ("Record not found");
else meibanlist.forEach (function(machine_unit){
console.log(machine_unit);
});
});
app.listen(3000);
console.log("Server running on port 3000");
To get the average air_temperature of all the machine_unit you can do it in following way, assuming your machine_unit is unique.
db.meibanlist.aggregate({$group: {_id: null,"average": {$avg: "$air_temperature"}}}).pretty()
In case you want to group the machine_unit and get average air_temperature on basis of machine_unit you can do it i following way
db.meibanlist.aggregate({$group: {_id: "$machine_unit","average": {$avg: "$air_temperature"}}}).pretty()
In case you have array stored in air_temperature and want to project and get average of air_temperature for each record. You can achieve it in following way:
db.meibanlist.aggregate({"$project": {"average": {$avg: "$air_temperature"}}}).pretty()