node.js - 如何使用 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 开始,我还没有找到一种方法来使用它。
解决方案
自从我使用 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" }
推荐阅读
- r - 如何将 R 中的日期列从最新到最早排序,然后将第一个条目作为向量读取?
- json - Sphinx 3 搜索引擎:从 CSV 源读取 JSON 时遇到问题
- java - 如何在构造函数中接受参数列表并将其添加到 Java 中的集合中?
- javascript - jQuery中最快的方法同时过滤“Radios + Select + Checkbox”
- r - Is it possible to add/subtract digits from a data frame column in R?
- reactjs - React - Uncaught SyntaxError: Identifier 'WBSAutoFillFormTypeUndetermined' has already been declared
- azure-devops - how to trigger pipeline from only feature/topic branch in azure devops?
- speech-recognition - Error occurred when extracting features using MFCC: Value Error: can't extend empty axis 0 using modes other than 'constant' or 'empty'
- linux - Why I can delete others' files on HDFS with only read permission
- docker-compose - docker swam - secrets from file not resolving tilde