0

I would like to aggregate from a collection with 2 fields:

var StatusSchema = mongoose.Schema({
    Demonstrator: SchemaTypes.Long, 
    DemoBetriebsbereit: Boolean
}

My aggregation function should aggregate by Demonstrator, as wells as by DemoBetriebsbereit field, and then count the occurences for each combination. The aggregation function looks like this:

    exports.getStatusDemonstrators = function(req,res) {
        Status.aggregate([
            {
                $match: {
                    "DemoBetriebsbereit": {$exists:1}
                }
            },
            {
                $group: {
                    _id: {Demonstrator: "$Demonstrator", betriebsbereit: 
                          "$DemoBetriebsbereit"}, Anzahl: {$sum:1}
                }
            }
        ]).exec(function(error, status) {
            if (error) {
                res.send(error);
            }
            else {
                res.json(status);
            }
        });
    }

The output is this:

[{"_id":{"Demonstrator":9,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":2,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":3,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":10,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":2,"betriebsbereit":true},"Anzahl":9},{"_id":{"Demonstrator":8,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":9,"betriebsbereit":true},"Anzahl":8},{"_id":{"Demonstrator":1,"betriebsbereit":true},"Anzahl":5},{"_id":{"Demonstrator":6,"betriebsbereit":true},"Anzahl":7},{"_id":{"Demonstrator":10,"betriebsbereit":true},"Anzahl":8},{"_id":{"Demonstrator":7,"betriebsbereit":false},"Anzahl":1},{"_id":{"Demonstrator":3,"betriebsbereit":true},"Anzahl":10}]

Hoewever, I would like the output to be like :

{Demonstrator:10, series: [{betriebsbereit: true, Anzahl: 8}, {betriebsbereit: false, Anzahl:1}]},{Demonstrator:9, series: [...]},...

in a format so that I can put it right directly inside a ngx-chart.

1 Answer 1

2

You need to add another $group step and then a $project.

This is the aggregation pipeline:

[
  {$match: {"DemoBetriebsbereit": {$exists: 1}}},
  { $group: {
    _id: {Demonstrator: "$Demonstrator", betriebsbereit: "$DemoBetriebsbereit"},
    Anzahl: {$sum: 1}
  }},
  { $group: {
     _id: "$_id.Demonstrator",
     series: {$push: {betriebsbereit: "$_id.betriebsbereit", Anzahl: "$Anzahl"}}
  }},
  {$project: {_id: 0, Demonstrator: "$_id", series: "$series"}}
]
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.