Home > Net >  show sub array as a final result
show sub array as a final result

Time:08-04

given query gives result as single object that contain array named data, and i want final output the content of that data array as root level like we do group by id and we get array entries as result.

db.demo.aggregate([
{
    '$group':
        {   '_id': null, 
            "Bytes Sent":{"$sum": "$sentBytes"},
            "Bytes Received":{"$sum":"$recivedBytes"}
        }
},
{
    "$project":{
        "data":[
                {"Count" :"$Bytes Sent","Name":"Bytes Sent"},
                {"Count" :"$Bytes Received","Name":"Bytes Received"}
               ] 
           }
       }
  ])

above query gives following output:

{
"_id" : null,
"data" : [
    {
        "Count" : NumberLong("22893994106"),
        "Name" : "Bytes Sent"
    },
    {
        "Count" : NumberLong("16574618640"),
        "Name" : "Bytes Received"
    }
]}

but i want a final result as array which has values of data array like below:

    {
        "Count" : NumberLong("22893994106"),
        "Name" : "Bytes Sent"
    },
    {
        "Count" : NumberLong("16574618640"),
        "Name" : "Bytes Received"
    }

how can i do that?

CodePudding user response:

Try to add these stages at the end of your aggregate:

{
    "$unwind": "$data"
},
{
    "$replaceRoot": {
        "newRoot": "$data"
    }
}

CodePudding user response:

Can't you just access the data object in the results to return just the object in that field?

db.demo.aggregate([
{
    '$group':
        {   '_id': null, 
            "Bytes Sent":{"$sum": "$sentBytes"},
            "Bytes Received":{"$sum":"$recivedBytes"}
        }
},
{
    "$project":{
        "data":[
                {"Count" :"$Bytes Sent","Name":"Bytes Sent"},
                {"Count" :"$Bytes Received","Name":"Bytes Received"}
               ] 
     }
}
])["data"]
  • Related