Search a document several times for a phrase or word

Let's say I have the following collection containing fields usernameand message:

{ 
    "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 ...

I can use the following code to get the top 10 usernames for which the word “hello” is most found in their posts:

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

The result is something like:

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

My question is how can I search each document (or field message) several times to get the total number of words "hello", and not just the number of documents that contain it at least once. Then the counter for "harry" will return 3 instead of 2. Thank you.

+4
source share

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


All Articles