title: How to make a MongoDB index to speed up key/value subdocuments sorting
body: <p>I have a collection with documents like this (simplified):</p>
  
  <pre><code>{
      _id: ObjectId("5099803df3f4948bd2f98391"),
      foo: "bar",
      data: [
          {
              "k": "userkey",
              "v": "uservalue"
          },
          {
              "k": "xpto",
              "v": "1234"
          }
      ]
  }
  </code></pre>
  
  <p>Data subdocument key and values are user defined and unpredictable. I am using this key-value to allow an index like this:</p>
  
  <pre><code>{ "data.k": 1, "data.v": 1 }
  </code></pre>
  
  <p>It works perfectly for querying on data subdocument, but I'm having a hard time to come up with an index to speed up sorting. Let's say I want to sort all documents by the "data.v" value from the elements containing "data.k" equals to "xpto", for example:</p>
  
  <pre><code>db.foo.aggregate([
      {
          $addFields: {
              dataAsObject: { $arrayToObject: "$data" },
          }
      },
      {
          $sort: {
              "dataAsObject.xpto": 1
          }
      }
  ])
  </code></pre>
  
  <p>It works, but it's making fullscans with poor performance. Does anybody have any idea on how to improve it?</p>