0

How can I rewrite this MongoDB query using the Aggregation Framework to return the average price for the following Model in between the supplied date range:

Model

var PriceSchema = new Schema({
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
};

Query

exports.getPriceAverage = function(req, res, next) {
    var start       = moment.utc('03-01-2012').startOf('day');
    var end         = moment.utc('03-01-2012').endOf('month')

    // Aggregation Framework Query Here...
    Price.find({ date: { $lt: end, $gt: start }}, function(err, priceAverage) {
         // Return average price...
    });
};

1 Answer 1

2

You mention using aggregation, but you're using the find function which would return all results to the client.

Instead, you need to use aggregate with $avg:

Price.aggregate([
    { $match: { date: { $lt: end, $gt: start } } },
    { $group: { _id: null, avgPrice: { $avg: '$price' } } }

], function(err, results){
   // process the results (an array of JavaScript objects)
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.