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;

您的困惑可能源于使用findfunctioncommandfunction之间的不同语法。

于 2013-01-23T07:36:30.153 回答