1

My Document Structure:

{
    "_id" : ObjectId("59edc58af33e9b5988b875fa"),
    "Agent" : {
        "Name" : "NomanAgent",
        "Location" : "Lahore",
        "AgentId" : 66,
        "Reward" : "Thumb Up",
        "Suggestion" : [ 
            "Knowledge", 
            "Professionalisn"
        ]
    }
}

What I want to achieve in this query: I want to find the count of each suggestion given by a customer to every agent, it should look something like,

{
    "AgentName": "Xyz",
    "SuggestionCounts": {
         "Knowledge": 2,
         "Professionalism": 3,
         "Friendliness": 1
     }
} 

What I have done so far,

db.getCollection('_survey.response').aggregate([
    {
        $group:{
            _id: "$Agent.Name",
            Suggestions: {$push:"$Agent.Suggestion"}
        }
    }
]);

Output:

/* 1 */
{
    "_id" : "GhazanferAgent",
    "Suggestions" : [ 
        [ 
            "Clarity", 
            "Effort"
        ], 
        [ 
            "Friendliness"
        ]
    ]
}

/* 2 */
{
    "_id" : "NomanAgent",
    "Suggestions" : [ 
        [ 
            "Knowledge", 
            "Professionalisn"
        ]
    ]
}

How I want it to be(As Suggestion in the document is an array and when when i group documents by Agent.Name so it become array of arrays as shown in my output, it want to merge all arrays into single with duplication and then i will find the count of each element in array):

/* 1 */
    {
        "_id" : "GhazanferAgent",
        "SuggestionsCombined" : [ 
            [ 
                "Clarity", 
                "Effort",
                "Friendliness"
            ]
        ]
    }

    /* 2 */
    {
        "_id" : "NomanAgent",
        "SuggestionsCombined" : [ 
            [ 
                "Knowledge", 
                "Professionalisn"
            ]
        ]
    }

Thanks in advance!!

1 Answer 1

1

One way would be like this - the output structure is not identical to what you suggested but probably close enough:

db.getCollection('_survey.response').aggregate([
    {
        $unwind: "$Agent.Suggestion" // flatten "Suggestion" array
    }, {
        $group:{ // group by agent and suggestion
            _id: { "AgentName": "$Agent.Name", "Suggestion": "$Agent.Suggestion" },
            "Count": { $sum: 1} // calculate count of occurrencs
        }
    }, {
        $group:{
            _id: "$_id.AgentName", // group by agent only
            "Suggestions": { $push: { "Suggestion": "$_id.Suggestion", "Count": "$Count" } } // create array of "Suggestion"/"Count" pairs per agent
        }
    }
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.