MongoDB aggregation to count words of strings' matches

Viewed 1670

Given the following MATCHES ($match) of an aggregation:

[
    "palabra": "Hello",
    "palabra": "My name is Rafael"
]

the next pipeline for aggregate gives me a total $sum of 2:

    var pipeline = [
        {
            $match: {
                "_p_evaluatedByUser": "_User$" + userId
            }
        },
        {
            $project: {
                palabra: 1
            }
        },
        {
            $unwind: "$palabra"
        },
        {
            $group: {
                _id: "result",
                count: {
                    $sum: 1
                }
            }
        }
    ];

I'm actually looking for a pipeline able to do $sum: $palabra.split(" ").length so it would be returning 5 instead of 2.

Is there any easy approach from my initial pipeline?

1 Answers
Related