title: Use distinct in php MongoDB query
body: <p>In my <code>cars_positions</code> database and <code>positions</code> collection I have this kind of data :</p>
  
  <p><code>db.positions.find()</code></p>
  
  <pre><code>{ "_id" : ObjectId("536a5cd9e9df25cd8609d286"), "car" : { "type" : "sport", "ref" : "nameOfTheCar1" }, "position" : { "dateTime" : "2014-05-06T06:42:10", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}
  { "_id" : ObjectId("536a5cd9e9df25cd8609d287"), "car" : { "type" : "sport", "ref" : "nameOfTheCar2" }, "position" : { "dateTime" : "2014-05-06T06:43:11", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}
  </code></pre>
  
  <p>I'm trying to use a distinct into my mongodb query. Here is my current query where I need to iterate all the data to create a proper array with only the last position:</p>
  
  <pre><code>    $pipeline = 
          [
              [
                  '$match' =&gt; 
                      [
                        'car.ref' =&gt; ['$in' =&gt; $cars],
                        'position.dateTime'  =&gt; 
                              [
                                  '$gte' =&gt; $period['start'],
                                  '$lte' =&gt; $period['end'],
                              ],
                      ],
              ],
              [
                  '$sort' =&gt; 
                      [
                        'position.dateTime' =&gt; 1,
                      ],
              ],
              [
                  '$group' =&gt; 
                      [
                        '_id' =&gt; ['car.ref'],
                        'lastposition' =&gt; ['$last' =&gt; '$position'],
                      ],
              ],
          ];
  
          $command = new \MongoDB\Driver\Command($pipeline);
          $cursor = $mongo-&gt;executeCommand('mybase.positions', $command);
  </code></pre>
  
  <p>Original post with the original query : <a href="http://pastebin.com/BEC7nUa7" rel="nofollow noreferrer">http://pastebin.com/BEC7nUa7</a></p>
  
  <p>What I would like to achieve is to have a distinct on the car.ref and only get the latest location of any car in the <code>$cars</code> array with the date range. </p>
  
  <p>So I could have a final array like this :</p>
  
  <pre><code>array (size=1)
    car1 =&gt; 
      array (size=8)
        'car.ref' =&gt; string 'car1' (length=7)
        'dateTime' =&gt; string '2017-01-18T00:00:09' (length=19)
        'latitude' =&gt; string '0000.1111' (length=9)
        'hemesphere' =&gt; string 'S' (length=1)
        'longitude' =&gt; string '05563.1254' (length=10)
     car2 =&gt;
     car3 =&gt;
  </code></pre>
  
  <p>Any idea ? Thanks !</p>