Tim
Tim

Reputation: 59

Mongoose aggregation sort dynamically

I want to sort dynamically by example avgTemperature or avgNoise but i cant do var sort = 'avgTemperature'; and get it in the aggregation. Does anyone have tips?

This is the static aggregation code it does only sort by avgTemperature. But i want to dynamically change.

 Measurement.aggregate([{
      $group: {
        _id: "$workplace",
        avgTemperature: {
          $avg: "$temperature"
        },
        avgNoise: {
          $avg: "$noise"
        }
      }
    }, {
      $sort: {
        avgTemperature: 1
      }
    }]);

Upvotes: 1

Views: 1678

Answers (1)

chridam
chridam

Reputation: 103305

Consider creating a document (or JS object) from the dynamic query to represent the $sort operator expression. You can use the square bracket notation to construct this.

Take the following example:

var sortOperator = { "$sort": { } },
    groupOperator = {
        "$group": {
            "_id": "$workplace",
            "avgTemperature": { "$avg": "$temperature" },
            "avgNoise": { "$avg": "$noise" }
        }
    },
    sort = "avgTemperature"; // <-- dynamic query

sortOperator["$sort"][sort] = 1; // <-- create sort operator using bracket notation
Measurement.aggregate([ groupOperator, sortOperator ])
           .exec(callback);

Upvotes: 1

Related Questions