This is a simple implementation of doctrine mongodb.
- git
- docker
- docker-compose
- makefile
Clone the project
git clone https://github.com/symfony-examples/doctrine-mongodb.git
Installation
make install-local
Enjoy ! 🥳
Add mongodb extension to php.ini
; mongodb.ini
extension=mongodb.so
Install mongodb driver
## INSTALL MONGODB DRIVER
RUN set -xe \
&& apk add --no-cache --update --virtual .phpize-deps $PHPIZE_DEPS openssl curl-dev openssl-dev \
&& pecl install mongodb
COPY ./.docker/php/mongodb.ini /usr/local/etc/php/conf.d/
Note : If you use flex, you need to run this command before installation of the
doctrine/mongodb-odm-bundle
package
composer config extra.symfony.allow-contrib true
Install the package
composer require doctrine/mongodb-odm-bundle
Show mongodb commands
./bin/console list doctrine:mongodb
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
#[ODM\Document(collection: 'Company')]
class Company
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
}
NOTE : don't add primary key to an embedded document
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
#[ODM\EmbeddedDocument]
class Registration
{
// without id
}
#[ODM\Document(collection: 'Company')]
class Company
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
#[ODM\EmbedOne(targetDocument: Registration::class)]
private Registration $registration;
}
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
#[ODM\EmbeddedDocument]
class Address
{
}
#[ODM\Document(collection: 'Company')]
class Company
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
#[ODM\EmbedMany(targetDocument: Address::class)]
private Collection $addresses;
public function __construct()
{
$this->addresses = new ArrayCollection();
}
}
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
#[ODM\Document(collection: 'Product')]
class Product
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
#[ODM\ReferenceOne(targetDocument: Store::class, cascade: 'persist')]
private Store $store;
}
#[ODM\Document(collection: 'Store')]
class Store
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
}
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
#[ODM\Document(collection: 'Store')]
class Store
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
#[ODM\ReferenceMany(targetDocument: Product::class, mappedBy: 'store')]
private Collection $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
}
#[ODM\Document(collection: 'Product')]
class Product
{
#[ODM\Id(type: 'string', strategy: 'auto')]
private ?string $id = null;
// inversedBy is optional, don't add it if you don't need the bi-directional reference
#[ODM\ReferenceOne(targetDocument: Store::class, cascade: 'persist', inversedBy: 'products')]
private Store $store;
}