如何基于$ group进行$ count和$ total多个字段

时间:2018-09-05 02:33:07

标签: 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的新手。如何复制上面的插图?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

基本上,您需要在此处多次使用$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>
      )
    })}
  )
})