Search for the most frequently used word in a string field in the entire collection

Say I have a Mongo compilation similar to the following:

[
  { "foo": "bar baz boo" },
  { "foo": "bar baz" },
  { "foo": "boo baz" }
]

Is it possible to determine which words appear most often in the field foo(ideally with a count)?

For example, I would like a result set of something like:

[
  { "baz" : 3 },
  { "boo" : 2 },
  { "bar" : 2 }
]
+4
source share
2 answers

The JIRA issue of the operator $splitthat will be used during $projectthe aggregation structure phase has recently been closed . <w> With this you can create such a conveyor

db.yourColl.aggregate([
    {
        $project: {
            words: { $split: ["$foo", " "] }
        }
    },
    {
        $unwind: {
            path: "$words"
        }
    },
    {
        $group: {
            _id: "$words",
            count: { $sum: 1 }
        }
    }
])
Result

will look like this

/* 1 */
{
    "_id" : "baz",
    "count" : 3.0
}

/* 2 */
{
    "_id" : "boo",
    "count" : 2.0
}

/* 3 */
{
    "_id" : "bar",
    "count" : 2.0
}
+5
source

MongoDB 3.4 $split , , $unwind , , $facet .

db.collection.aggregate([
    { "$facet": { 
        "results": [ 
            { "$project": { 
                "values": { "$split": [ "$foo", " " ] }
            }}, 
            { "$unwind": "$values" }, 
            { "$group": { 
                "_id": "$values", 
                "count": { "$sum": 1 } 
            }} 
        ]
    }}
])

:

{
    "results" : [
        {
            "_id" : "boo",
            "count" : 2
       },
       {
            "_id" : "baz",
            "count" : 3
       },
       {
            "_id" : "bar",
            "count" : 2
       }
   ]
}

MongoDB 3.2 , - mapReduce.

var reduceFunction = function(key, value) { 
    var results = {}; 
    for ( var items of Array.concat(value)) { 
        for (var item of items) {
            results[item] = results[item] ? results[item] + 1 : 1;
        } 
    }; 
    return results; 
}

db.collection.mapReduce(
    function() { emit(null, this.foo.split(" ")); }, 
    reduceFunction, 
    { "out": { "inline": 1 } } 
)

:

{
    "results" : [
        {
            "_id" : null,
            "value" : {
                "bar" : 2,
                "baz" : 3,
                "boo" : 2
            }
        }
    ],
    "timeMillis" : 30,
    "counts" : {
        "input" : 3,
        "emit" : 3,
        "reduce" : 1,
        "output" : 1
    },
    "ok" : 1
}

.forEach() , MongoDB for...of .

0

Source: https://habr.com/ru/post/1650066/


All Articles