多次搜索文档以查找短语或单词

时间:2015-05-21 20:43:00

标签: javascript mongodb

说我有以下集合,其中包含字段usernamemessage

{ 
    "username" : "bob", 
    "message" : "testing hello"
}
{ 
    "username" : "harry", 
    "message" : "hello hello"
}
{ 
    "username" : "harry", 
    "message" : "hi hello"
}
{ 
    "username" : "tom", 
    "message" : "hello there"
}
{ 
    "username" : "john", 
    "message" : "hey"
}

etc ...

我可以使用以下代码获取前10个用户名,其中“hello”一词在其消息中出现次数最多:

db.collection('collectionName').aggregate(
    { $match : { message: /hello/ } }, 
    { $group : { _id: '$username', count: { $sum: 1 } } }, 
    { $sort : { count : -1 } }, 
    { $limit : 10 }, 
function(err, results) {
    console.log(results);
});

这导致类似:

{ _id: 'harry', count: 2 },
{ _id: 'bob', count: 1 },
{ _id: 'tom', count: 1 }

我的问题 - 如何多次搜索每个文档(或message字段)以检索单词“hello”的总计数,而不仅仅是包含它的文档数量至少一次。然后“哈里”的计数将返回3而不是2.谢谢。

0 个答案:

没有答案