javascript - 如何根据$group对多个字段进行$count和$total

标签 javascript node.js mongodb mongoose aggregation-framework

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

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

这是我要显示的插图。 enter image description here

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

最佳答案

你可以试试下面的聚合

基本上你需要使用$group在这里多次上演。

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

关于javascript - 如何根据$group对多个字段进行$count和$total,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176272/

相关文章:

javascript - 我如何在 redux-saga 中以有限的并发性和理智的取消来实现批处理任务?

javascript - IE 是否支持 jQuery 的 prop 方法

javascript - 如何使用 jQuery 选择具有特定 ARIA 值的所有元素?

javascript - 当我向/api/users/login发送POST请求时,用户未定义

mongodb - 使用 mongodb 和 redis 的缓存失效策略

c# - 设置默认 DateTime.Now 值以在保存文档时保存到 MongoDB

javascript - 单页 JavaScript 应用程序的唯一 URL?

javascript - 从链式 Promise 返回映射数组

javascript - Node.js Web 套接字服务器 : Is my idea for data management stable/scalable?

javascript - Javascript 中的 Excel 到 JSON 模式