Reputation: 1482
My document is a little complicated, it is like:
{
'_id': 1,
'words':
{
'a':
{
'positions': [1,2,3],
'count':3,
},
'and':
{
'positions': [4, 5],
'count': 2,
}
}
}
I have many ducuments that contains very same words, I want aggregate all the fields in words
. To give it me like:
{
'a': 5 #a's sum count
'and': 6 #and's sum count
}
I read this article, MongoDB - group composite key with nested fields, but unluckily, the structure is different, what they do is group the array field, not the nested field.
Any advice? Hope your answer and help, thanks in advance.
Upvotes: 2
Views: 1720
Reputation: 49945
You can try following aggregation:
db.col.aggregate([
{
$project: {
wordsAsKeyValuePairs: {
$objectToArray: "$words"
}
}
},
{
$unwind: "$wordsAsKeyValuePairs"
},
{
$group: {
_id: "$wordsAsKeyValuePairs.k",
count: { $sum: "$wordsAsKeyValuePairs.v.count"}
}
}
])
To aggregate over your fields you need to use $objectToArray to decompose object into array of key-value pairs. Then we're just $unwinding such array to be able to group by k which is single word and sum all the counts.
Upvotes: 2