1
votes

I'm using PHP and MongoDB to sore and to get the nearest points to my position. But I have a problem.

When I use the mongo console, it returns values but when I'm doing by PHP code, it returns a null object.

PHP Code:

$connection = new MongoClient( "mongodb://localhost" );
$db = $connection->collection;
$collection = $db->user_location;

// There are many differnt queries (by token, by email...)
if (isset($_GET['email'])) {
    $query = array(
    //'email' => array( '$neq' => $_GET['email']),
    'loc' => array(
        '$near' => array(
        'lon' => floatval($_GET['longitude']),
        'lat' => floatval($_GET['latitude']), 
        '$maxDistance' => intval($_GET['distance']))));
}

$maxDistance = $_GET["distance"];
$lon = $_GET['longitude'];
$lat = $_GET['latitude'];

$cursor = $collection->find($query);
if ($cursor) {
    echo json_encode($cursor);
} else {
    echo "{ 'status' : 'false' }";
}

This is an example of mongo console use: db.user_location.ensureIndex({ loc : "2d"} )

db.user_location.find() { "_id" : ObjectId("51dbe817617c6df061000000"), "email" : "zgz", "loc" : { "lon" : -0.88588498, "lat" : 41.68035677 }, "date" : "Tue, 09 Jul 2013 06:38:15" } db.user_location.find({"loc": {"$near": {"lon":-0.88588498,"lat":41.68035677}, "$maxDistance":99}}) { "_id" : ObjectId("51dbe817617c6df061000000"), "email" : "zgz", "loc" : { "lon" : -0.88588498, "lat" : 41.68035677 }, "date" : "Tue, 09 Jul 2013 06:38:15" }

If I use the same values in my PHP code, it returns a null cursor. Why? Thanks!

2
There's no need to add "SOLVED" to your questions here: this is not a forum, it's a Q&A site: answers are separate entities: so you can add your own answer, and select it as 'accepted'. You can remove the answer from your question :)Nanne
NO worries, +1 for your answer :DNanne

2 Answers

1
votes

According to this MongoDB $near doc query should look like this:

$query = array(    
    'loc' => array(
        '$near' => array(
            floatval($_GET['longitude']),
            floatval($_GET['latitude']), 
        )
        '$maxDistance' => intval($_GET['distance'])),
    ),
);

And you should check $_GET['longtitude'] and so on with isset function before calling.

1
votes

I have the solution.

The problem I had was that I was trying to return $cursor directly but $collection->find($query) returns more than 1 object (note that $findOne() returns only 1, so you are not going to be problem to return $cursor). In that case (with find()), you need to return iterator_to_array($cursor).

$cursor = $collection->find($query);
if ($cursor) {
    echo json_encode(iterator_to_array($cursor));
} else {
    echo "{ 'status' : 'false' }";
}