Monogdb中的$ facet聚合 [英] $facet aggregation in monogdb

查看:128
本文介绍了Monogdb中的$ facet聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例数据如下:

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

我对所有group categories创建了一个聚合查询,并得到如下所示的计数:

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

我得到的输出如下:

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

但是,我需要将此数据group到下一个级别才能获得如下输出:

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

Category      count
Privacy         2
Mobile          2
Others          3

在此,前两个类别(具有较高计数,即隐私权"和移动")被假定为强项,而其余所有类别被假定为弱点并称为其他弱点. Others应该动态计算,它是除强数据点之外的所有其他数据点的加法运算.

关于此的任何建议或指示可能会有所帮助?

注意:我正在使用mongodb 3.6

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

更新:JSON示例

{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),

推荐答案

您应该尝试$facet聚合以获得所需的结果,该结果非常容易与limitskip ...

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

这篇关于Monogdb中的$ facet聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆