# How to aggregate sub documents

**URL:** <https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [November 25, 2021, 1:51pm UTC](https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184 "2021-11-25T13:51:20Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Aleem\_Ktk](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/aleem_ktk/32/97607_2.png) [@Aleem\_Ktk](https://discuss.elastic.co/u/Aleem_Ktk)\
**Post date:** [November 25, 2021, 1:51pm UTC](https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184/1 "2021-11-25T13:51:20Z")

</div>

I have sub documents in the main document , below is the format:  
"activities:[  
{  
"code": "CODE1",  
"price":20  
},  
{  
"code": "CODE2",  
"price":24  
}  
]

I want to sum the price group by code. However, the term aggregates query give result for CODE1:44 instead 20. because the sum aggs is sum up the price field for all inner documents.

Any help will be appreciated.

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [November 25, 2021, 2:48pm UTC](https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184/2 "2021-11-25T14:48:38Z")

</div>

May be use `nested` type for nested documents?  
Have a look at [Nested field type | Elasticsearch Guide [7.15] | Elastic](https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html)

---

<div class="post-metadata">

**Author:** ![Aleem\_Ktk](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/aleem_ktk/32/97607_2.png) [@Aleem\_Ktk](https://discuss.elastic.co/u/Aleem_Ktk)\
**Post date:** [November 26, 2021, 9:47am UTC](https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184/3 "2021-11-26T09:47:09Z")

</div>

Thanks @dadoonet . nested aggregation is the solution. Because the nested aggregation treats the sub documents as main document. This may be the reason.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [December 24, 2021, 9:47am UTC](https://discuss.elastic.co/t/how-to-aggregate-sub-documents/290184/4 "2021-12-24T09:47:48Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
