title: Mongo incorrectly sorting on array field?
body: <p>I'm trying to filter on an array field which unfortunately doesn't seem to be working correctly. Everything I've read suggests that this should work, and the sort is doing <em>something</em>, just not what I expected and I can't explain it.</p>
  
  <p>What I'm trying to achieve is sorting on an array sub-field. I've managed to achieve most of this using the positional operator but I can't work out what the sort is doing.</p>
  
  <pre><code>db.getCollection('boards')
    .find({ "lastVisited.user": "AAA" }, { name: 1, "lastVisited.$" : 1 })
    .sort({ "lastVisited.0.timestamp": 1 });
  </code></pre>
  
  <p>This results in the following output</p>
  
  <pre><code>/* 1 */
  {
      "_id" : ObjectId("5b642d2cac2f544b1d48d09a"),
      "lastVisited" : [ 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-18T00:00:00.000Z")
          }
      ]
  }
  
  /* 2 */
  {
      "_id" : ObjectId("5b6845245e102f3844d2181b"),
      "lastVisited" : [ 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-16T00:00:00.000Z")
          }
      ]
  }
  
  /* 3 */
  {
      "_id" : ObjectId("5b6842095e102f3844d2181a"),
      "lastVisited" : [ 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-19T00:00:00.000Z")
          }
      ]
  }
  </code></pre>
  
  <p>The thing to note here is that the dates are ordered <code>18th</code> then <code>19th</code> then <code>16th</code> which makes no sense! Can anyone explain this?</p>
  
  <p>These are the documents that I've used:</p>
  
  <pre><code>/* 1 */
  {
      "_id" : ObjectId("5b642d2cac2f544b1d48d09a"),
      "lastVisited" : [ 
          {
              "user" : "BBB",
              "timestamp" : ISODate("2018-08-04T00:00:00.000Z")
          }, 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-18T00:00:00.000Z")
          }
      ]
  }
  
  /* 2 */
  {
      "_id" : ObjectId("5b6842095e102f3844d2181a"),
      "lastVisited" : [ 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-19T00:00:00.000Z")
          }
      ]
  }
  
  /* 3 */
  {
      "_id" : ObjectId("5b6845245e102f3844d2181b"),
      "lastVisited" : [ 
          {
              "user" : "AAA",
              "timestamp" : ISODate("2018-08-16T00:00:00.000Z")
          }
      ]
  }
  </code></pre>