【问题标题】:How to $count and $total multiple fields based on $group如何根据 $group 对多个字段进行 $count 和 $total
【发布时间】:2019-02-10 01:49:55
【问题描述】:

大家好。我有想要分组的示例数据。

{ 
"_id" : ObjectId("5b8de8e635da281e1cb6279b"), 
"CountryName" : "Spain", 
"SmartClassification": "Special Focus"
}
{ 
"_id" : ObjectId("5b8de8e635da281e1cb6279c"), 
"CountryName" : "Malaysia", 
"SmartClassification": "Investment Focus"
}
{ 
"_id" : ObjectId("5b8de8e635da281e1cb6279c"), 
"CountryName" : "Nigeria", 
"SmartClassification": "Fundamental Focus"
}

这是我想要展示的插图。

我想按“CountryName”及其“SmartClassifications”的总数对上面的数据进行$group。这对我来说很棘手,因为我对 MongoDB 比较陌生。如何重现上面的插图?

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    你可以试试下面的聚合

    基本上这里需要多次使用$groupstage。

    db.collection.aggregate([
      { "$group": {
        "_id": {
          "CountryName": "$CountryName",
          "SmartClassification": "$SmartClassification"
        },
        "count": { "$sum": 1 }
      }},
      { "$group": {
        "_id": "$_id.CountryName",
        "data": {
          "$push": {
            "SmartClassification": "$_id.SmartClassification",
            "count": "$count"
          }
        }
      }}
    ])
    

    你会得到这样的数据

    const myData = [
      { "_id": "Spain", "data": [{ "SmartClassification": "Special Focus", "count": 1 }] },
      { "_id": "Malaysia", "data": [{ "SmartClassification": "Investment Focus", "count": 1 }] },
      { "_id": "Nigeria", "data": [{ "SmartClassification": "Fundamental Focus", "count": 2 }] }
    ]
    

    现在您可以遍历数据并在您的 html 页面上显示类似的内容

    myData.map((country) => {
      return(
        <div>{country._id}</div>
        {country.data.map((da) => {
          return(
            <div>{da.SmartClassification}</div>
            <div>{da.count}</div>
          )
        })}
      )
    })
    

    【讨论】:

    • 嗨@Anthony。如何使输出不显示 _id 而显示两个属性?
    • 这将为您提供按 CountryNameSmartClassification 分组的数据,然后您可以循环输出并显示您在屏幕截图中显示的内容
    • 非常感谢。它有效,我可以遍历所有这些。
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2019-10-16
    • 2021-03-08
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多