我在Mongo有一套文件.说:

[
    { summary:"This is good" },
    { summary:"This is bad" },
    { summary:"Something that is neither good nor bad" }
]

我想计算每个单词出现的次数(不区分大小写),然后按降序排序.结果应该是:

[
    "is": 3,
    "bad": 2,
    "good": 2,
    "this": 2,
    "neither": 1,
    "nor": 1,
    "something": 1,
    "that": 1
]

知道怎么做吗?聚合框架将是首选,因为我已经在某种程度上理解了它:)

推荐答案

MapReduce可能是一个很好的 Select ,它可以在服务器上处理文档,而无需在客户机上进行操作(因为DB服务器上没有拆分字符串的功能(open issue).

map函数开始.在下面的示例中(可能需要更健壮),每个文档都会传递给map函数(as this).代码查找summary字段,如果有,则将其小写,在空格上拆分,然后为找到的每个单词发送1.

var map = function() {  
    var summary = this.summary;
    if (summary) { 
        // quick lowercase to normalize per your requirements
        summary = summary.toLowerCase().split(" "); 
        for (var i = summary.length - 1; i >= 0; i--) {
            // might want to remove punctuation, etc. here
            if (summary[i])  {      // make sure there's something
               emit(summary[i], 1); // store a 1 for each word
            }
        }
    }
};

然后,在reduce函数中,它对map函数找到的所有结果求和,并为上面列出的每个单词返回一个离散的总数.

var reduce = function( key, values ) {    
    var count = 0;    
    values.forEach(function(v) {            
        count +=v;    
    });
    return count;
}

最后,执行mapReduce:

> db.so.mapReduce(map, reduce, {out: "word_count"})

结果和您的样本数据:

> db.word_count.find().sort({value:-1})
{ "_id" : "is", "value" : 3 }
{ "_id" : "bad", "value" : 2 }
{ "_id" : "good", "value" : 2 }
{ "_id" : "this", "value" : 2 }
{ "_id" : "neither", "value" : 1 }
{ "_id" : "or", "value" : 1 }
{ "_id" : "something", "value" : 1 }
{ "_id" : "that", "value" : 1 }

Mongodb相关问答推荐

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

MongoDB聚合:如何将查找结果放入嵌套数组中?

MongoDB - 使用许多嵌套对象更新嵌套数组

没有mongoose 的 Express 和 MongoDB

Spring Data + MongoDB GridFS 可以通过 Repository 访问吗?

TypeError:Cannot read property '_id' of undefined

Ruby on Rails 的 Cassandra、mongodb 或 couchdb

Mongodb插入没有_id字段的文档

Flask and Mongo

字段类型在 MongoDB 索引中是否重要?

如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?

Golang + MongoDB 嵌入类型(将一个 struct 嵌入到另一个 struct 中)

将 mongodb 聚合框架结果导出到新集合

MongoDB - 我如何找到另一个集合中的文档未引用的所有文档

在 MongoDB 中插入或更新许多文档

在 MongoDB 上分片 GridFS

查询 Mongoid/rails 3 中的嵌入对象(Lower than、Min 运算符和排序)

指定在 mongodb .js 脚本中使用哪个数据库

处理Mongodb连接的正确方法是什么?

在 NodeJs 中处理 Mongodb 全局连接的最佳方法是什么