【问题标题】:$facet aggregation in monogdbmongodb 中的 $facet 聚合
【发布时间】:2018-10-21 23:32:26
【问题描述】:

我的示例数据如下所示:

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

我创建了一个聚合查询到group all categories 并得到如下计数:

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 将此数据到下一级才能获得如下输出:

Category      count
Privacy         2
Mobile          2
Others          3

这里,前两个类别(计数较高,即隐私和移动)被假定为强,其余所有类别都被假定为弱点并称为其他类别Others 应动态计算,即除强数据点外的所有其他数据点的相加。

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

注意:我使用的是 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),

【问题讨论】:

  • 如果把mongodb样本集合放在这里会更好
  • 我猜你要的是 JSON 样本,如果是,我已经更新了问题。请查看问题中的更新部分以获取示例。

标签: mongodb aggregation-framework


【解决方案1】:

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

可以查看输出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" }}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2020-11-09
    • 1970-01-01
    • 2019-01-14
    • 2012-05-10
    相关资源
    最近更新 更多