$facet aggregation in monogdb

流过昼夜 提交于 2019-12-24 08:16:09

问题


My Sample data looks like below:

Category      response
Privacy         1
Mobile          1
Privacy         1
Privacy         0
Phishing        1
Mobile          1
Desktop         1
Desktop         0
Security        1

I have created an aggregate query to group all categories and get the count as below:

db.cmi5DashboardData.aggregate([
{$group:{_id:'$category',knt:{$sum:'$response'}}},
{$sort:{knt:-1}},
{$project:{_id:0,category:'$_id',count:'$knt'}}
])

I get the output as below:

Category      count
Privacy         2
Mobile          2
Phishing        1
Desktop         1
Security        1

However, I need to group this data to next level to get the output as below:

Category      count
Privacy         2
Mobile          2
Others          3

Here, first two categories(with higher count i.e. Privacy & Mobile) are assumed as strong and rest all categories are assumed as weak points and termed as others . Others should be calculated dynamically which is an addition of all other data points except strong data points.

Any suggestions or pointers on this could be helpful?

Note: I'm using mongodb 3.6

Update: JSON Samples

{Category:'Phishing', response:1),
{Category:'Security', response:1),
{Category:'Privacy', response:1),
{Category:'Privacy', response:1),
{Category:'Privacy', response:0),
{Category:'Mobile', response:1),
{Category:'Mobile', response:1),
{Category:'Desktop', response:1),
{Category:'Desktop', response:0),

回答1:


You should try $facet aggregation to get the desired result which pretty simple to use with limit and skip...

You can check the output here

db.collection.aggregate([
  { "$facet": {
    "top": [
      { "$group": {
        "_id": "$Category",
        "response": { "$sum": "$response" }
      }},
      { "$sort": { "response": -1 }},
      { "$limit": 2 }
    ],
    "rest": [
      { "$group": {
        "_id": "$Category",
        "response": { "$sum": "$response" }
      }},
      { "$sort": { "response": -1 }},
      { "$skip": 2 },
      { "$group": {
        "_id": "Others",
        "response": { "$sum": "$response" }
      }}
    ]
  }},
  { "$project": { "data": { "$concatArrays": ["$top", "$rest"] }}},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }}
])


来源:https://stackoverflow.com/questions/50294184/facet-aggregation-in-monogdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!