gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:13:21 25 4
gpt4 key购买 nike

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

{ 
"_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com