0

I have to make an auto suggest on city level so that i have list cities of mapped with respective countries like USA => ( "New York", "Dallas", "Los Angeles" .....)

what i need is to save it in mongodb with symfony2 mapping method. I searched a lot but not able to find proper help or documentation regarding array handling in mongodb.

Please explain if any has some experience in this area.

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;
}

}

Usage to insert:

    $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();

Inserted Record:

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

Code Used to Retrieve:

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

But i am not able get the record by above retrieval code.....

4

1 回答 1

0

如果您需要通过ObjectId类型的id检索 City,您必须从MongoId 创建对象并将您的 id 作为字符串

例子:

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

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

    var_dump($city);
于 2014-01-15T17:45:29.173 回答