使用Symfony2的MongoDB

时间:2013-10-07 13:21:01

标签: mongodb symfony odm

我必须在城市级别进行自动建议,以便列出与USA => ( "New York", "Dallas", "Los Angeles" .....)

等相应国家/地区相对应的列表城市

我需要的是用symfony2映射方法将它保存在mongodb中。 我搜索了很多,但无法在mongodb中找到有关阵列处理的适当帮助或文档。

请解释是否有任何在该领域的经验。

namespace SPTL\UserBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
* @MongoDB\Document
*/
class City {
/**
 * @MongoDB\Id
 */
protected $id;

/**
 * @MongoDB\String
 */
protected $country;

/**
 * @MongoDB\hash
 */
protected $city = array();


/**
 * Get id
 *
 * @return id $id
 */
public function getId()
{
    return $this->id;
}

/**
 * Set country
 *
 * @param string $country
 * @return \City
 */
public function setCountry($country)
{
    $this->country = $country;
    return $this;
}

/**
 * Get country
 *
 * @return string $country
 */
public function getCountry()
{
    return $this->country;
}

/**
 * Set city
 *
 * @param hash $city
 * @return \City
 */
public function setCity($city)
{
    $this->city = $city;
    return $this;
}

/**
 * Get city
 *
 * @return hash $city
 */
public function getCity()
{
    return $this->city;
}

}

要插入的用法:

    $dm = $this->get('doctrine_mongodb')->getManager();
    $cities = new City();
    $cities->setCountry("USA");
    $cities->setCity(array("New York", "Dallas", "Los Angeles"));
    $dm->persist($cities);
    $dm->flush();

插入记录:

{
 "_id": ObjectId("5252b03f6b0f57394e2fb1b5"),
 "country": "USA",
 "city": {
  "0": "New York",
  "1": "Dallas",
  "2": "Los Angeles"  
  } 
}

用于检索的代码:

$repository = $this->get('doctrine_mongodb')->getManager()
    ->getRepository('UserBundle:City');
$cities = $repository->findBy(array("_id"=>'5252b03f6b0f57394e2fb1b5'));
print_r($cities);

但是我无法通过上面的检索代码得到记录.....

1 个答案:

答案 0 :(得分:0)

如果您需要按 ObjectId 类型的 id 检索城市 你必须从MongoId创建对象并将你的id作为字符串

示例:

    $repository = $this->get('doctrine_mongodb')->getManager()
        ->getRepository('UserBundle:City');

    $cityId = new \MongoId("5252b03f6b0f57394e2fb1b5");
    $city = $repository->find($cityId);

    var_dump($city);