Use distinct in php MongoDB query

Use distinct in php MongoDB query

In my cars_positions database and positions collection I have this kind of data :
db.positions.find()
{ “_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”}}

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:
$pipeline =
[
[
‘$match’ =>
[
‘car.ref’ => [‘$in’ => $cars],
‘position.dateTime’ =>
[
‘$gte’ => $period[‘start’],
‘$lte’ => $period[‘end’],
],
],
],
[
‘$sort’ =>
[
‘position.dateTime’ => 1,
],
],
[
‘$group’ =>
[
‘_id’ => [‘car.ref’],
‘lastposition’ => [‘$last’ => ‘$position’],
],
],
];

$command = new \MongoDB\Driver\Command($pipeline);
$cursor = $mongo->executeCommand(‘mybase.positions’, $command);

Original post with the original query : http://pastebin.com/BEC7nUa7
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 $cars array with the date range.
So I could have a final array like this :
array (size=1)
car1 =>
array (size=8)
‘car.ref’ => string ‘car1’ (length=7)
‘dateTime’ => string ‘2017-01-18T00:00:09’ (length=19)
‘latitude’ => string ‘0000.1111’ (length=9)
‘hemesphere’ => string ‘S’ (length=1)
‘longitude’ => string ‘05563.1254’ (length=10)
car2 =>
car3 =>

Related:  Connecting Heroku App to Atlas MongoDB Cloud service

Any idea ? Thanks !

Solutions/Answers:

Solution 1:

You will need aggregation. Try something like below.

<?php

    $mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $cars = ['nameOfTheCar1', 'nameOfTheCar2'];

    $start = new \MongoDB\BSON\UTCDateTime(strtotime('2012-05-06T06:42:10') * 1000);
    $end = new \MongoDB\BSON\UTCDateTime(strtotime('2014-05-06T06:42:10') * 1000);   

    $pipeline = 
        [
            [
                '$match' => 
                    [
                      'car.ref' => ['$in' => $cars],
                      'position.dateTime'  => 
                            [
                                '$gte' => $start,
                                '$lte' => $end,
                            ],
                    ],
            ],
            [
                '$sort' => 
                    [
                      'position.dateTime' => 1,
                    ],
            ],
            [
                '$group' => 
                    [
                      '_id' => '$car.ref',
                      'lastposition' => ['$last' => '$position'],
                    ],
            ],
        ];

    $command = new \MongoDB\Driver\Command([
        'aggregate' => 'positions', 
        'pipeline' => $pipeline
        ]);

    $cursor = $mongo->executeCommand('mybase', $command);

    foreach($cursor as $key => $document) {
        var_dump($document);

    }
?>

References