2013-01-23 17 views
0

我有一個非常簡單的PHP函數,它應該返回的東西最接近的位置,基於傳遞給它的座標:MongoDB的抱怨缺少的二維地理空間索引,但它似乎存在

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似乎在locationCollectionlocation字段的正確2d指數:

{ 
    "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 }' 

任何想法?謝謝!

回答

1

我想你查詢應該是這樣的:

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

你的困惑可以從不同的語法使用find functioncommand function之間所產生。

+0

謝謝,這個伎倆! –

相關問題