0

渡された座標に基づいて、物の最も近い場所を返すことになっている非常に単純な PHP 関数があります。

private function getLocationClosestTo($longitude, $latitude) {
    /**
     * NOTE: I've found some conflicting documentation about '$geoNear'.
     * Some say to use the field name in the collection, others say to use
     * the collection name. I've tried both 'location' and 'locationCollection'
     * and both have resulted in the same error. Seems like the field name
     * would be correct, since the collection name is specified before ->find().
     */
    $query= array('$geoNear' => 'location', '$near' => array($longitude, $latitude), '$num' => 1, '$spherical' => true);
    $cursor = $this->db->locationCollection->find($query);

    $location = null;
    // unnecessary, but I can clean it up
    foreach($cursor as $doc) {
        $location = $doc;
    }

    return $location;
}

の内容locationCollectionはとてもシンプルです。ドキュメントの例を次に示します。

{
   "_id": ObjectId("50ff04be7139fa2bbaf8f3cb"),
   "number": "100",
   "store_name": "Baz",
   "street": "Bar",
   "city": "Foo",
   "state": "CA",
   "zip": "98057",
   // plus a few other fields, and finally, the important stuff:
   "location": {
     "longitude": -122.2171, // MongoDB wants longitude first (x then y)
     "latitude": 47.4829 
  }
}

次のコマンドでインデックスを作成しました:db.locationCollection.ensureIndex({"location" : "2d" })で、フィールドにsystem.indexes適切な2dインデックスがあるようです:locationlocationCollection

{
   "v": 1,
   "key": {
     "location": "2d" 
  },
   "ns": "dbName.locationCollection",
   "name": "location_" 
}

それでも、コードを実行すると、次のエラーが発生します。

Uncaught exception 'MongoCursorException' with message 'can't find special index: 2d for: { $geoNear: "location", $near: [ -122.4194, 37.7749 ], $num: 1, $spherical: true }'

何か案は?ありがとう!

4

1 に答える 1

1

クエリは次のようにする必要があると思います:

$query= array('location' => array('$nearSphere' => array($longitude, $latitude)));
$location = $this->db->locationCollection->findOne($query);
return $location;

あなたの混乱は、関数の使用とfind関数の構文の違いに起因している可能性がありcommandます

于 2013-01-23T07:36:30.153 に答える