title: Elasticsearch - Aggregation sort by metric
body: <p>I have the following documents:</p>
  
  <pre><code>POST index/type
  {
    "profile": {
      "tracks": [
        {
          "title": "Track 1",
          "count": 5
        },
        {
          "title": "Track 2",
          "count": 3
        }
      ]
    }
  }
  
  POST index/type
  {
    "profile": {
      "tracks": [
        {
          "title": "Track 2",
          "count": 8
        },
        {
          "title": "Track 3",
          "count": 1
        }
      ]
    }
  }
  
  POST index/type
  {
    "profile": {
      "tracks": [
        {
          "title": "Track 4",
          "count": 20
        },
        {
          "title": "Track 5",
          "count": 1
        }
      ]
    }
  }
  </code></pre>
  
  <p>where "count" property in each track item is the number of times user has played that particular track.</p>
  
  <p>I would like to have a list of tracks order by number of times they are played. So in the example above, expected results would be:</p>
  
  <pre><code>[
    {
      "key": "Track 4",
      "count": {
         "value": 20
      }
    },
    {
      "key": "Track 2",
      "count": {
         "value": 11
      }
    },
    {
      "key": "Track 1",
      "count": {
         "value": 5
      }
    },
    {
      "key": "Track 3",
      "count": {
         "value": 1
      }
    },
    {
      "key": "Track 5",
      "count": {
         "value": 1
      }
    }
  ]
  </code></pre>
  
  <p>I have tried:</p>
  
  <pre><code>"aggs": {
    "track_count": {
      "terms": {
          "field": "profile.tracks.title",
          "order": {
              "count": "desc"
          }
      },
      "aggs": {
          "count": {
              "sum": {
                  "field": "profile.tracks.count"
              }
          }
      }
    }
  }
  </code></pre>
  
  <p>But it does not seem to be correct since the the count is calculated by summing all other count properties of each track item.</p>
  
  <p>I do not know how to build my aggregation so that the count value is calculated by summing count properties of the same track across other documents.</p>
  
  <p>Any help will be greatly appreciated. Thank you.</p>