1

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
      }
    }]);

1 Answer 1

1

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);
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.