Reputation: 1176
My MongoDB stores documents having the following structure:
{
"curl_detail" : {
"Curl1" : {
"attack_type" : "attack1",
"flag" : "Attack",
"curl_result" : "Pass"
},
"Curl2" : {
"attack_type" : "attack1",
"flag" : "Attack",
"curl_result" : "Pass"
},
"Curl3" : {
"attack_type" : "attack2",
"flag" : "Attack",
"curl_result" : "Pass"
},
"Curl4" : {
"attack_type" : "attack3",
"flag" : "Attack",
"curl_result" : "Fail"
}
}
{
"curl_detail" : {
"Curl1" : {
"attack_type" : "attack3",
"flag" : "Attack",
"curl_result" : "Pass"
},
"Curl2" : {
"attack_type" : "attack2",
"flag" : "Attack",
"curl_result" : "Pass"
},
"Curl3" : {
"attack_type" : "attack3",
"flag" : "Pass",
"curl_result" : "Pass"
},
"Curl4" : {
"attack_type" : "attack1",
"flag" : "Attack",
"curl_result" : "Fail"
}
}
How can I perform MongoDB aggregation to achieve the following output:
[{
attack: "attack1",
expected: 3,
actual: 2
},
{
attack:"attack2",
expected: 2,
actual: 2
},
{
attack: "attack3",
expected: 2,
actual: 2
}]
Explanation for output required:
Upvotes: 1
Views: 89
Reputation: 46481
You can use below aggregation
db.collection.aggregate([
{ "$addFields": {
"curl_detail": {
"$objectToArray": "$curl_detail"
}
}},
{ "$unwind": "$curl_detail" },
{ "$group": {
"_id": "$curl_detail.v.attack_type",
"expected": {
"$sum": {
"$cond": [
{ "$eq": ["$curl_detail.v.flag", "Attack"] },
1,
0
]
}
},
"actual": {
"$sum": {
"$cond": [
{ "$eq": ["$curl_detail.v.curl_result", "Pass"] },
1,
0
]
}
}
}},
{ "$addFields": { "attack": "$_id", "_id": "$$REMOVE" }}
])
Upvotes: 1