[英]MongoDB aggregation group by query
我有一個 mongoDB 集合,我想做一個聚合查詢。
我按alert_type
字段進行分組,但我還希望將這些alert_type
列表作為 output 中的單獨字段。
集合看起來像這樣:
db.test.insertMany([
{
"output_data": {
"alert_type": "UAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
},
{
"output_data": {
"alert_type": "CAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
},
{
"output_data": {
"alert_type": "UAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
}
])
我嘗試過的查詢:
db.test.aggregate([
{$group: {
"_id": "$output_data.alert_type",
"alert_type": {
"$first": "$output_data.alert_type"
},
"margin": {
"$sum": "$output_data.overallImpact.margin"
},
"workingCapital": {
"$sum": "$output_data.overallImpact.workingCapital"
},
"alert_types": {
"$addToSet": "$output_data.alert_type"
}
}
},
{$project: {'_id': 0
}
}
])
當前 output :
{
"alert_type": "UAlert",
"margin": 0.2,
"workingCapital": 6.66,
"alert_types": [
"UAlert"
]
}
{
"alert_type": "CAlert",
"margin": 0.1,
"workingCapital": 3.33,
"alert_types": [
"CAlert"
]
}
需要 Output :
{
"data": [
{
"alert_type": "UAlert",
"margin": 0.2,
"workingCapital": 6.66,
},
{
"alert_type": "CAlert",
"margin": 0.1,
"workingCapital": 3.33,
}
],
"alert_types": [
"UAlert",
"CAlert"
]
}
誰能幫我解決這個問題?
您必須使用$facet來實現這一點,在一個階段您進行分組階段以獲取數據,而在另一個階段您可以找到所有可用的警報類型。
db.collection.aggregate([
{
$facet: {
data: [
{
$group: {
"_id": "$output_data.alert_type",
"alert_type": {
"$first": "$output_data.alert_type"
},
"margin": {
"$sum": "$output_data.overallImpact.margin"
},
"workingCapital": {
"$sum": "$output_data.overallImpact.workingCapital"
},
}
},
{
$project: {
"_id": 0
}
}
],
"alert_types": [
{
$group: {
_id: null,
"names": {
"$addToSet": "$output_data.alert_type"
}
}
}
]
}
},
{
$project: {
data: 1,
alert_types: "$alert_types.names"
}
}
])
你可以在這里測試
您可以嘗試以下聚合查詢:
db.collection.aggregate([
{
$group: {
"_id": "$output_data.alert_type",
alert_type: { $first: "$output_data.alert_type" },
margin: { $sum: "$output_data.overallImpact.margin" },
workingCapital: { $sum: "$output_data.overallImpact.workingCapital" }
}
},
/** Optional stage - Just to exclude `_id` inside each object of data array from final output */
{
$project: { _id: 0 }
},
/** Grouping on all docs, For this group stage we will have lesser docs compared to prior Group stage */
{
$group: {
_id: "", // Group without any condition
data: { $push: "$$ROOT" }, // Pushing all docs into an array
alert_types: { $addToSet: "$alert_type" } // Adding unique values
}
},
/** Optional stage - Just to exclude `_id` final output doc */
{
$project: { _id: 0 }
}
])
測試: mongoplayground
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.