How do I add an object into MongoDB using Doctrine?

3k views Asked by At

I use Doctrine Mongo db bundle with Symfony2. Information about string, int etc data types in the Doctrine Mongodb documents. But, I could not find object data types.

The question: How do I add an object into MongoDB using Doctrine? How do I define (object type) in the document class?

3

There are 3 answers

0
Calimero On

Assuming by "Object" you mean document (mongodb) or Hash (javascript), or in other words a Key-value array, then see field type hash in doctrine-mongo docs.

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

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

0
shacharsol On

You simply define a class with @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;
  }

 }

Then to create the document use document manager:

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

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