首页 > 解决方案 > 如何使用 node.js 和 mongoose 计算一组文档中的词频

问题描述

我在 MongoDB 中有一组文档。

在此处输入图像描述

在带有 mongoose 的NodeJS中,我想计算每个单词的出现次数。结果应该是这样的:

[
    "latest": 2,
    "sprint": 2,
    "lair": 1,
    "laugh": 1,
    "fault": 1,
    "lemma": 2,
    "on": 1,
]

知道如何使用 MongoDB 聚合框架来做到这一点吗?

我读到聚合框架具有更好的性能,因为聚合在服务器 (C++) 中本机运行,而 mapReduce 产生单独的 javascript 线程来运行 JavaScript 代码。但我从 MongoDB 开始,我还没有找到一种方法来使用它。

标签: node.jsmongodbmongooseaggregation-framework

解决方案


自从我使用 Mongo 以来已经有一段时间了,但希望这会有所帮助:

db.TestDocuments.aggregate([

  // Unwind each element of the array into its own document
  { $unwind: "$words" },

  // Group and count the total of each occurrence for each word
  { $group: { 
    _id: "$words" , 
    count: { "$sum": 1 }
  }},

  // Remove the id field from the response, rename it to the word
  { $project: { "_id": 0, "word": "$_id", "count": 1 } },

  // Sort the results with highest occurrences first
  { $sort: { "count": -1 } }
]);

这种结构的结果:

{ "count" : 2, "word" : "latest" }
{ "count" : 2, "word" : "sprint" }
{ "count" : 2, "word" : "lemma" }
{ "count" : 1, "word" : "lair" }
{ "count" : 1, "word" : "laugh" }
{ "count" : 1, "word" : "fault" }
{ "count" : 1, "word" : "on" }

推荐阅读