KhorneHoly KhorneHoly - 1 year ago 121
PHP Question

How to use geoNear with the current PHP MongoDB Driver?

I'm currently working with the current PHP MongoDB\Driver .

I need to use an

geoNear
query to fetch points from my current location. The required
2dsphere index
is already set, the query works in the console and delivers multiple results:

db.runCommand({geoNear: 'pois', near: [ 52.264633, 6.12485 ], spherical: true, maxDistance: 1000, distanceField: 'distance'})


Since the previous methods are deprecated, I can't use the old
aggregate
functions.

I'm now trying to find the right way to build the query I need with the current
Query
or
Command
classes.

What I've tried is the following:

$query = array(
'geoNear' => 'pois',
"near" => array(
52.264633,
6.12485
),
"spherical" => true,
"maxDistance" => 1000,
"distanceField" => "distance"
);
$cmd = new MongoDB\Driver\Command($query);
$returnCursor = $this->conn->executeCommand("database.pois", $cmd);
$arrReturn = $returnCursor->toArray();
return $arrReturn;


If I use this, I will return this Runtime Error:

"exception": [
{
"type": "MongoDB\\Driver\\Exception\\RuntimeException",
"code": 18,
"message": "Failed to decode document from the server."
}
]"


I couldn't find a solution for my case and also I couldn't find more information to this error.

If I change the
Command
up to a
Query
, the execution doesn't fail, but there are no results.

My mongodb is on the version 3.2, my PHP version is PHP Version 7.0.16-4+deb.sury.org~trusty+1 and the mongodb Exension is version 1.2.3

Answer Source

You can use the aggregate in the following way with new driver.

$pipeline = array(array(
    '$geoNear'=> array(
    'near' => array(
        52.264633,
        6.12485
    ),
    'spherical' => true,
    'maxDistance' => 1000,
    'distanceField' => "distance"
)));

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

$returnCursor = $this->conn->executeCommand("database", $cmd);
$arrReturn = $returnCursor->toArray();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download