MongoDB Support

Overview

MongoDB is one of the most popular NoSQL document-oriented database, used for its high write load (useful for analytics or IoT) and high availability (easy to set replica sets with automatic failover). It can also shard the database easily for horizontal scalability and has a powerful query language for doing aggregation, text search or geospatial queries.

MongoDB は、最も人気のある NoSQL ドキュメント指向データベースの 1 つであり、高い書き込み負荷 (分析や IoT に役立つ) と高可用性 (自動フェイルオーバーでレプリカ セットを簡単に設定できる) のために使用されます。また、水平方向のスケーラビリティのためにデータベースを簡単に分割でき、集計、テキスト検索、または地理空間クエリを実行するための強力なクエリ言語を備えています。

API Platform uses Doctrine MongoDB ODM 2 and in particular its aggregation builder to leverage all the possibilities of the database.

API プラットフォームは、Doctrine MongoDB ODM 2 と、特にその集約ビルダーを使用して、データベースのすべての可能性を活用します。

Doctrine MongoDB ODM 2 relies on the mongodb PHP extension and not on the legacy mongo extension.

Doctrine MongoDB ODM 2 は、従来の mongo 拡張機能ではなく、mongodb PHP 拡張機能に依存しています。

Enabling MongoDB Support

If the mongodb PHP extension is not installed yet, install it beforehand.

mongodb PHP 拡張機能がまだインストールされていない場合は、事前にインストールしてください。

If you are using the API Platform Distribution, modify the Dockerfile to add the extension:

API プラットフォーム ディストリビューションを使用している場合は、Dockerfile を変更して拡張機能を追加します。

# api/Dockerfile
  pecl install \
   apcu-${APCU_VERSION} \
+  mongodb \
  ; \
  pecl clear-cache; \
  docker-php-ext-enable \
   apcu \
+  mongodb \
   opcache \
  ; \

Then rebuild the php image:

次に、php イメージを再構築します。

docker compose build php

Add a MongoDB image to the docker-compose file:

MongoDB イメージを docker-compose ファイルに追加します。

# docker-compose.yml
# ...
  db-mongodb:
      # In production, you may want to use a managed database service
      image: mongo
      environment:
          - MONGO_INITDB_DATABASE=api
          - MONGO_INITDB_ROOT_USERNAME=api-platform
          # You should definitely change the password in production
          - MONGO_INITDB_ROOT_PASSWORD=!ChangeMe!
      volumes:
          - db-data:/data/db:rw
          # You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
          # - ./docker/db/data:/data/db:rw
      ports:
          - "27017:27017"
# ...

Once the extension is installed, to enable the MongoDB support, require the Doctrine MongoDB ODM bundle package using Composer:

拡張機能をインストールしたら、MongoDB サポートを有効にするには、Composer を使用して Doctrine MongoDB ODM bundlepackage を要求します。

docker compose exec php \
    composer require doctrine/mongodb-odm-bundle

Execute the contrib recipe to have it already configured.

contrib レシピを実行して、すでに構成されているようにします。

Change the MongoDB environment variables to match your Docker image:

Docker イメージに合わせて MongoDB 環境変数を変更します。

# api/.env
MONGODB_URL=mongodb://api-platform:!ChangeMe!@db-mongodb
MONGODB_DB=api

Change the configuration of API Platform to add the right mapping path:

API プラットフォームの構成を変更して、正しいマッピング パスを追加します。

# api/config/packages/api_platform.yaml
api_platform:
    # ...

    mapping:
        paths: ['%kernel.project_dir%/src/Entity', '%kernel.project_dir%/src/Document']

    # ...

Creating Documents

Creating resources mapped to MongoDB documents is as simple as creating entities:

MongoDB ドキュメントにマップされたリソースの作成は、エンティティの作成と同じくらい簡単です。

<?php
// api/src/Document/Product.php

namespace App\Document;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ODM\Document
 */
#[ApiResource]
class Product
{
    /**
     * @ODM\Id(strategy="INCREMENT", type="int")
     */
    private $id;

    /**
     * @ODM\Field
     */
    #[Assert\NotBlank]
    public $name;

    /**
     * @ODM\ReferenceMany(targetDocument=Offer::class, mappedBy="product", cascade={"persist"}, storeAs="id")
     */
    public $offers;

    public function __construct()
    {
        $this->offers = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function addOffer(Offer $offer): void
    {
        $offer->product = $this;
        $this->offers->add($offer);
    }

    public function removeOffer(Offer $offer): void
    {
        $offer->product = null;
        $this->offers->removeElement($offer);
    }

    // ...
}
<?php
// api/src/Document/Offer.php

namespace App\Document;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ODM\Document
 */
#[ApiResource(types: ['https://schema.org/Offer'])]
class Offer
{
    /**
     * @ODM\Id(strategy="INCREMENT", type="int")
     */
    private $id;

    /**
     * @ODM\Field
     */
    public $description;

    /**
     * @ODM\Field(type="float")
     * @Assert\NotBlank
     * @Assert\Range(min=0, minMessage="The price must be superior to 0.")
     * @Assert\Type(type="float")
     */
    public $price;

    /**
     * @ODM\ReferenceOne(targetDocument=Product::class, inversedBy="offers", storeAs="id")
     */
    public $product;

    public function getId(): ?int
    {
        return $this->id;
    }
}

When defining references, always use the ID for storing them instead of the native DBRef. It allows API Platform to manage filtering on nested properties by using lookups.

参照を定義するときは、ネイティブの DBRef ではなく、それらを保存するために常に ID を使用します。これにより、API プラットフォームはルックアップを使用して、ネストされたプロパティのフィルタリングを管理できます。

Filtering

Doctrine MongoDB ODM filters are practically the same as Doctrine ORM filters.

Doctrine MongoDB ODM フィルターは Doctrine ORM フィルターと実質的に同じです。

See how to use them and how to create custom ones in the filters documentation.

フィルターのドキュメントで、フィルターの使用方法とカスタム フィルターの作成方法を参照してください。

Creating Custom Extensions

See how to create Doctrine MongoDB ODM custom extensions in the extensions documentation.

拡張機能のドキュメントで Doctrine MongoDB ODM カスタム拡張機能を作成する方法を参照してください。

Adding Execute Options

If you want to add some command options when executing an aggregate query (see the related documentation in MongoDB manual), you can do it in your resource configuration, at the operation or the resource level.

集計クエリを実行するときにいくつかのコマンド オプションを追加する場合 (MongoDB マニュアルの関連ドキュメントを参照)、操作またはリソース レベルで、リソース構成で行うことができます。

For instance at the operation level:

たとえば、操作レベルでは次のようになります。

<?php
// api/src/Document/Offer.php

namespace App\Document;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
#[ApiResource]
#[GetCollection(extraProperties: ['doctrineMongodb' => ['execute_options' => ['allowDiskUse' => true]]])]
class Offer
{
    // ...
}

Or at the resource level:

またはリソース レベルで:

<?php
// api/src/Document/Offer.php

namespace App\Document;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
#[ApiResource(extraProperties: ['doctrineMongodb' => ['execute_options' => ['allowDiskUse' => true]]])]
class Offer
{
    // ...
}