Прошло много времени с тех пор, как я использовал 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" }