Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

This example depends on a single document and shows us how to use MongoDB as database for our application. For more info visit DoctrineMongoDBBundle, QueryBuilder API, Reference Mapping and Working with Objects.


Installation


Assuming that you already have MongoDB installed in your OS and enabled in php.ini files.


Composer.json


{
"require": {
"doctrine/mongodb-odm": "1.0.*@dev",
"doctrine/mongodb-odm-bundle": "3.0.*@dev"
},
}

Composer update


php composer.phar update doctrine/mongodb-odm doctrine/mongodb-odm-bundle

Autoload.php


# app/autoload.php
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
AnnotationDriver::registerAnnotationClasses();

AppKernel.php


# app/AppKernel.php
new Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle(),

Configuration


# app/config/config.yml
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}

default_database: inanzzz_mongodb_database
document_managers:
default:
auto_mapping: true
retry_connect: 3
retry_query: 3

Run MongoDB


inanzzz$ mongod

Controllers.yml


services:
application_nosql.controller.default:
class: Application\NosqlBundle\Controller\DefaultController
arguments:
- @doctrine_mongodb.odm.default_document_manager
- @application_nosql.repository.default

Repositories.yml


services:
application_nosql.repository.default:
class: Application\NosqlBundle\Repository\DefaultRepository
factory: [@doctrine_mongodb, getRepository]
arguments: [Application\NosqlBundle\Document\League]

Controller


For now, I've just kept all in controller below but in real life, you should use service, model and factory classes along with controller to divide the logic.


namespace Application\NosqlBundle\Controller;

use Application\NosqlBundle\Document\League;
use Application\NosqlBundle\Repository\LeagueRepository;
use DateTime;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
* @Route("/league", service="application_nosql.controller.default")
*/
class DefaultController extends Controller
{
private $documentManager;
private $leagueRepository;

public function __construct(
DocumentManager $documentManager,
LeagueRepository $leagueRepository
) {
$this->documentManager = $documentManager;
$this->leagueRepository = $leagueRepository;
}

/**
* @param Request $request
*
* @Route("")
* @Method({"POST"})
*
* @return Response
*/
public function createLeagueAction(Request $request)
{
$league = new League();
$league->setName($request->request->get('name'));

$this->documentManager->persist($league);
$this->documentManager->flush();

return new Response('League ID:'.json_encode($league->getId()));
}

/**
* @Route("")
* @Method({"GET"})
*
* @return Response
*/
public function getAllLeagueAction()
{
$leagues = $this->leagueRepository->findAll();

$i = 0;
$result = [];
foreach ($leagues as $league) {
$result[$i]['id'] = (string)$league->getId();
$result[$i]['name'] = $league->getName();
$result[$i]['createdAt'] = $league->getCreatedAt()->format(DateTime::ISO8601);

$i++;
}

return new Response(json_encode($result));
}

/**
* @param string $property
* @param string $data
*
* @Route("/{property}/{data}")
* @Method({"GET"})
*
* @return Response
*/
public function getOneLeagueAction($property, $data)
{
$league = $this->leagueRepository->findOneByProperty($property, $data);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with %s [%s] cannot be found.', $property, $data)
);
}

$result['id'] = (string)$league->getId();
$result['name'] = $league->getName();
$result['createdAt'] = $league->getCreatedAt()->format(DateTime::ISO8601);

return new Response(json_encode($result));
}

/**
* @param Request $request
* @param string $id
*
* @Route("/{id}")
* @Method({"PATCH"})
*
* @return Response
*/
public function updateLeagueAction(Request $request, $id)
{
$league = $this->leagueRepository->findOneByProperty('id', $id);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with id [%s] cannot be found.', $id)
);
}

$league->setName($request->request->get('name'));

$this->documentManager->flush();

return new Response('League ID:'.$id);
}

/**
* @param string $id
*
* @Route("/{id}")
* @Method({"DELETE"})
*
* @return Response
*/
public function deleteLeagueAction($id)
{
$league = $this->leagueRepository->findOneByProperty('id', $id);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with id [%s] cannot be found.', $id)
);
}

$this->documentManager->remove($league);
$this->documentManager->flush();

return new Response('League ID:'.$id);
}
}

League document


namespace Application\NosqlBundle\Document;

use DateTime;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Date;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Id;

/**
* @MongoDB\Document(collection="league", repositoryClass="Application\NosqlBundle\Repository\LeagueRepository")
* @MongoDB\HasLifecycleCallbacks
*/
class League
{
/**
* @MongoDB\Id
*/
private $id;

/**
* @MongoDB\String
*/
private $name;

/**
* @MongoDB\Date
*/
private $createdAt;

/**
* @MongoDB\Date
*/
private $updatedAt;

/**
* @MongoDB\PrePersist
*/
public function onPrePersist()
{
$this->createdAt = new DateTime();
}

/**
* @MongoDB\PreUpdate
*/
public function onPreUpdate()
{
$this->updatedAt = new DateTime();
}

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

/**
* @param string $name
*
* @return self
*/
public function setName($name)
{
$this->name = $name;

return $this;
}

/**
* @return string $name
*/
public function getName()
{
return $this->name;
}

/**
* @return date $createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}

/**
* @return date $updatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
}

Repository


namespace Application\NosqlBundle\Repository;

use Doctrine\ODM\MongoDB\DocumentRepository;

class LeagueRepository extends DocumentRepository
{
/**
* @return mixed
*/
public function findAll()
{
return
$this->createQueryBuilder('League')
->sort('createdAt', 'desc')
->getQuery()
->execute();
}

/**
* @param string $field
* @param string $data
*
* @return array|null|object
*/
public function findOneByProperty($field, $data)
{
return
$this->createQueryBuilder('League')
->field($field)->equals($data)
->getQuery()
->getSingleResult();
}
}

Usages


Create


POST /app_dev.php/nosql/league
{
"name": "inanzzz"
}

Find one


GET /nosql/league/id/564bb9fcdd576e1ef90041ab
{
"id": "564bb9fcdd576e1ef90041ab",
"name": "inanzzz3",
"createdAt": "2015-11-17T23:36:28+0000"
}

List all


GET /nosql/league
[
{
"id": "564bb9fcdd576e1ef90041ab",
"name": "inanzzz3",
"createdAt": "2015-11-17T23:36:28+0000"
},
{
"id": "564bb9f8dd576e1ef90041aa",
"name": "inanzzz2",
"createdAt": "2015-11-17T23:36:24+0000"
},
{
"id": "564bb9f4dd576e1ef90041a9",
"name": "inanzzz1",
"createdAt": "2015-11-17T23:36:20+0000"
}
]

Update one


PATCH /nosql/league/564bb9f8dd576e1ef90041aa
{
"name": "inanzzz2u"
}

Delete one


DELETE /nosql/league/564bb9f4dd576e1ef90041a9