How to group data in a single object with new keys after a $ mongodb group?

advertisements

I have a mongodb database with a collection of companies that look like this (it's just a sample, the actual collection is much larger):

[
  {
    "_id": 100,
    "name": "Test Name 1",
    "level": "1"
  },
  {
    "_id": 101,
    "name": "Test Name 2",
    "level": "1"
  },
  {
    "_id": 102,
    "name": "Test Name 3",
    "level": "2"
  }
]

Where "level" can only range from 0 to 5

I'm trying to make an aggregate query with $group and $project that counts how many companies there are in each level, but according to the API specification I need follow, it needs to be formatted like this, in a single object:

{
  "metrics": {
    "companies": {
      "total": <integer>,
      "level1": <integer>,
      "level2": <integer>,
      "level3": <integer>,
      "level4": <integer>,
      "level5": <integer>
    }
  }
}

The closest I could get to this was using $group and $project like this:

Companies.aggregate([{
            $group: {
                _id: {
                    level: "$level"
                },
                count: {
                    $sum: 1
                }
            }
        },
        {
            $project: {
                _id: 0,
                level: "$_id.level",
                total: "$count"
            }
        }
    ])

Which gives the following result:

[
  {
    "level": 3,
    "total": 108
  },
  {
    "level": 5,
    "total": 172
  },
  {
    "level": 2,
    "total": 624
  },
  {
    "level": 4,
    "total": 98
  },
  {
    "level": 1,
    "total": 137
  },
  {
    "level": 0,
    "total": 94
  }
]

However, this result is an array and I need to put the data for each level in a single object with new keys "level1", "level2", etc, according to the specification.

I believe I need to make another $group operation but I couldn't find out how to do it.

Any ideas?


I'm not sure If I understand, but I suppose you just need to map it, like here:

> var aux = new Object;
> db.Companies.aggregate([
  {
    $group: {
      _id: {
        level: "$level"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      level: "$_id.level",
      total: "$count"
    }
  }
]).forEach(function(a){aux["level"+a.level] = a.total;});
> printjson(aux);
{ "level2" : 1, "level1" : 2 }