how to get keyword cloud from mongodb? -


i have many documents in following format

{     _id:...,     words:["usa","canda","america", "colon"],     owner:23 } {     _id:...,     words:["chile","peru","argentina","america", "colon"],     owner:23 } {     _id:...,     words:["colon", "america", "britain", "mexico", "usa"],     owner:23 } 

so, need keyword cloud owner 23:

[     {name:"america", hits:3},     {name:"colon", hits:3},     {name:"usa", hits:2},     {name:"britain", hits:1},     {...} ] 

my problem can not want. how can get? thanks

use aggregation framework give after. aggregation pipeline should have $match operator first step filters input documents on owner key has value 23. second pipeline step $unwind operator deconstructs words array field input documents , outputs next stream document each element. each output document replaces array element value.

the pipeline stage gives keyword count $group operator groups input documents previous stream word key , applies accumulator expression $sum returns sum each group.

the last step, $project operator reshapes each document in stream adding new field name replaces _id key previous stream.

in end, aggregation pipeline this:

db.collection.aggregate([     {         "$match": { "owner": 23 }     },     {         "$unwind": "$words"     },     {         "$group": {             "_id": "$words",             "hits": {                 "$sum": 1             }         }     },     {         "$project": {             "_id": 0, "name": "$_id", "hits": 1         }     } ]) 

Comments