我有一个非常简单的 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
上有正确的索引:location
locationCollection
{
"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 }'
有任何想法吗?谢谢!