MongoDB聚合计算字符串匹配的单词

时间:2017-07-23 15:38:42

标签: mongodb aggregation-framework

给出以下聚合的匹配($match):

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

pipeline的下一个aggregate给了我{2}的$sum总数:

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

我实际上正在寻找一个pipeline $sum: $palabra.split(" ").length能够5,而不是2

我最初的pipeline是否有任何简单的方法?

1 个答案:

答案 0 :(得分:1)

在你的$ unwind之后:

    {
        $project: {
           "words": {$split: ["$palabra", " "]}
        }
    },
    {
        $unwind: "$words"
    },
    {
        $group: {
          _id: null,
          allwords: {$push: "$words"}
        }
    },
    {
        $project: {
            wordCount: {$size: "$allwords"}
        }
    }