如何使用Doctrine将对象添加到MongoDB中?

时间:2013-12-23 15:10:06

标签: mongodb symfony doctrine-orm doctrine-mongodb

我使用Doctrine Mongo db bundle和Symfony2。有关Doctrine Mongodb文档中的字符串,int等数据类型的信息。但是,我找不到对象数据类型。

问题:如何使用Doctrine将对象添加到MongoDB中?如何在文档类中定义(对象类型)?

3 个答案:

答案 0 :(得分:2)

您只需使用@MongoDB \ Document annotation定义一个类:

<?php

namespace Radsphere\MissionBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
 * @MongoDB\Document(
 *      collection="user_statistics",
 *      repositoryClass="Radsphere\MissionBundle\DocumentRepository\UserStatisticsRepository",
 *      indexes={
 *          @MongoDB\Index(keys={"user_profile_id"="asc"})
 *      }
 *  )
 */
 class UserStatistics
 {


 /**
  * @var \MongoId
  *
  * @MongoDB\Id(strategy="AUTO")
  */
 protected $id;
 /**
  * @var string
  *
  * @MongoDB\Field(name="user_profile_id", type="int")
  */
 protected $userProfileId;
 /**
  * @var integer
  *
  * @MongoDB\Field(name="total_missions", type="int")
  */
 protected $totalMissions;
 /**
  * @var \DateTime
  *
  * @MongoDB\Field(name="issued_date", type="date")
  */
  protected $issuedDate;

  /**
   *
   */
  public function __construct()
  {
     $this->issuedDate = new \DateTime();
  }

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

  /**
  * {@inheritDoc}
  */
  public function getIssuedDate()
  {
    return $this->issuedDate;
  }

  /**
   * {@inheritDoc}
  */
  public function setIssuedDate($issuedDate)
  {
     $this->issuedDate = $issuedDate;
  }

  /**
   * {@inheritDoc}
  */
  public function getTotalMissions()
  {
    return $this->totalMissions;
  }

  /**
   * {@inheritDoc}
  */
  public function setTotalMissions($totalMissions)
  {
    $this->totalMissions = $totalMissions;
  }

  /**
   * {@inheritDoc}
  */
  public function getUserProfileId()
  {
    return $this->userProfileId;
  }

  /**
   * {@inheritDoc}
  */
  public function setUserProfileId($userProfileId)
  {
    $this->userProfileId = $userProfileId;
  }

 }

然后创建文档使用文档管理器:

    $userStatisticsDocument = new UserStatistics();
    $userStatisticsDocument->setUserProfileId($userProfile->getId());

    $userStatisticsDocument->setTotalMissions($totalMissions);
    $userStatisticsDocument->setIssuedDate(new \DateTime('now'));
    $this->documentManager->persist($userStatisticsDocument);
    $this->documentManager->flush($userStatisticsDocument);

答案 1 :(得分:1)

假设“对象”是指文档(mongodb)或哈希(javascript),或者换句话说是键值数组,那么请参阅doctrine-mongo docs中的字段类型哈希。

/**
 * @Field(type="hash")
 */
protected $yourvariable;

http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/annotations-reference.html

答案 2 :(得分:1)