spideytest1
docs
DistributionAPI componentSchema componentAdmin componentScaffolding componentDeployment
Demo
News
Support

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.

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

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

Enabling MongoDB support

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

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

 // api/Dockerfile

 ...
 	pecl install \
 		apcu-${APCU_VERSION} \
+		mongodb \
 	; \
 ...
 	docker-php-ext-enable \
 		apcu \
 		opcache \
+		mongodb \
 	; \
 ...

Then rebuild the php image:

docker-compose build php

Add a MongoDB image to the docker-compose file:

# 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:/var/lib/mongodb/data: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:/var/lib/mongodb/data:rw
      ports:
          - "27017:27017"
# ...

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

docker-compose exec php composer req doctrine/mongodb-odm-bundle:^4.0.0@beta doctrine/mongodb-odm:^2.0.0@beta

Execute the contrib recipe to have it already configured.

Change the MongoDB environment variables to match your Docker image:

# 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/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:

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

namespace App\Document;

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

/**
 * @ApiResource
 *
 * @ODM\Document
 */
class Product
{
    /**
     * @ODM\Id(strategy="INCREMENT", type="integer")
     */
    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\Core\Annotation\ApiResource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ApiResource(iri="http://schema.org/Offer")
 *
 * @ODM\Document
 */
class Offer
{
    /**
     * @ODM\Id(strategy="INCREMENT", type="integer")
     */
    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;
}

Some important information about the mapping:

  • Identifier fields always need to be integer with an increment strategy. API Platform does not support the native ObjectId.
  • 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.

Filtering

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

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.

You can also help us improving the documentation of this page.

Pushing Live Updates Using the Mercure ProtocolElasticsearch Support

The Distribution: Create Powerful APIs with Ease

  • Getting Started with API Platform: Hypermedia and GraphQL API, Admin and Progressive Web App
    • Installing the Framework
      • Using the Official Distribution (recommended)
      • Using Symfony Flex and Composer (advanced users)
    • It's Ready!
    • Bringing your Own Model
    • Validating Data
    • Adding GraphQL Support
    • The Admin
    • A React/Redux Progressive Web App
    • Other Features
  • Testing and Specifying the API
    • Running Unit Tests with PHPUnit
  • Debugging
    • Add a Development Stage to the Dockerfile
    • Configure Xdebug with Docker Compose Override
    • Troubleshooting

The API Component

  • The API Platform Core Library
    • Features
    • Other resources
  • Getting started
    • Installing API Platform Core
    • Before Reading this Documentation
    • Mapping the Entities
  • General Design Considerations
  • Operations
    • Enabling and Disabling Operations
    • Configuring Operations
      • Prefixing All Routes of All Operations
    • Subresources
      • Control the Path of Subresources
      • Access Control of Subresources
      • Control the Depth of Subresources
    • Creating Custom Operations and Controllers
      • Recommended Method
        • Serialization Groups
        • Entity Retrieval
      • Alternative Method
  • GraphQL Support
    • Overall View
    • Enabling GraphQL
    • GraphiQL
    • Filters
      • Filtering on Nested Properties
    • Security (access_control)
    • Serialization Groups
  • Filters
    • Doctrine ORM and MongoDB ODM Filters
      • Basic Knowledge
      • Search Filter
      • Date Filter
        • Managing null Values
      • Boolean Filter
      • Numeric Filter
      • Range Filter
      • Exists Filter
      • Order Filter (Sorting)
        • Comparing with Null Values
        • Using a Custom Order Query Parameter Name
      • Filtering on Nested Properties
      • Enabling a Filter for All Properties of a Resource
    • Elasticsearch Filters
      • Ordering Filter (Sorting)
        • Using a Custom Order Query Parameter Name
      • Match Filter
      • Term Filter
      • Filtering on Nested Properties
    • Serializer Filters
      • Group Filter
      • Property filter
    • Creating Custom Filters
      • Creating Custom Doctrine ORM Filters
      • Creating Custom Doctrine MongoDB ODM Filters
      • Creating Custom Elasticsearch Filters
      • Using Doctrine ORM Filters
    • ApiFilter Annotation
  • The Serialization Process
    • Overall Process
    • Available Serializers
    • The Serialization Context, Groups and Relations
      • Configuration
    • Using Serialization Groups
    • Using Serialization Groups per Operation
      • Embedding Relations
      • Denormalization
    • Changing the Serialization Context Dynamically
    • Changing the Serialization Context on a Per-item Basis
    • Name Conversion
    • Decorating a Serializer and Adding Extra Data
    • Entity Identifier Case
    • Embedding the JSON-LD Context
  • Validation
    • Validating Submitted Data
    • Using Validation Groups
    • Using Validation Groups on Operations
    • Dynamic Validation Groups
    • Error Levels and Payload Serialization
  • Security
    • Configuring the Access Control Message
  • Data Providers
    • Custom Collection Data Provider
    • Custom Item Data Provider
    • Injecting the Serializer in an ItemDataProvider
    • Injecting Extensions (Pagination, Filter, EagerLoading etc.)
  • Data Persisters
    • Creating a Custom Data Persister
  • Pushing Live Updates Using the Mercure Protocol
    • Installing the Mercure Support
    • Pushing the API Updates
    • Dispatching Private Updates (Authorized Mode)
  • MongoDB Support
    • Overview
    • Enabling MongoDB support
    • Creating documents
    • Filtering
    • Creating custom extensions
  • Elasticsearch Support
    • Overview
    • Enabling reading support
    • Creating models
      • Creating custom mapping
    • Filtering
    • Creating custom extensions
  • Pagination
    • Disabling the Pagination
      • Globally
      • For a Specific Resource
      • Client-side
        • Globally
        • For a specific resource
    • Changing the Number of Items per Page
      • Globally
      • For a Specific Resource
      • Client-side
        • Globally
        • For a Specific Resource
    • Changing Maximum items per page
      • Globally
      • For a Specific Resource
      • For a Specific Resource Collection Operation
    • Partial Pagination
      • Globally
      • For a Specific Resource
      • Client-side
        • Globally
        • For a Specific Resource
    • Avoiding double SQL requests on Doctrine ORM
    • Custom Controller Action
  • The Event System
  • Content Negotiation
    • Enabling Several Formats
    • Enabling Additional Formats On a Specific Resource/Operation
    • Registering a Custom Serializer
    • Writing a Custom Normalizer
  • Deprecating Resources and Properties (Alternative to Versioning)
    • Deprecating Resource Classes, Operations and Properties
    • Setting the Sunset HTTP Header to Indicate When a Resource or an Operation Will Be Removed
  • Performance and Cache
    • Enabling the Built-in HTTP Cache Invalidation System
      • Extending Cache-Tags for invalidation
    • Setting Custom HTTP Cache Headers
    • Enabling the Metadata Cache
    • Using PPM (PHP-PM)
    • Doctrine Queries and Indexes
      • Search Filter
      • Eager Loading
        • Max Joins
        • Force Eager
        • Override at Resource and Operation Level
        • Disable Eager Loading
      • Partial Pagination
    • Profiling with Blackfire.io
  • Extensions
    • Custom Doctrine ORM Extension
      • Example
        • Blocking Anonymous Users
    • Custom Doctrine MongoDB ODM Extension
    • Custom Elasticsearch Extension
  • OpenAPI Specification Support (formerly Swagger)
    • Using the OpenAPI Command
    • Overriding the OpenAPI Specification
    • Using the OpenAPI and Swagger Contexts
    • Changing the Name of a Definition
    • Changing Operations in the OpenAPI Documentation
    • Changing the Location of Swagger UI
      • Disabling Swagger UI or of ReDoc
      • Manually Registering the Swagger UI Controller
    • Overriding the UI Template
    • Compatibilily Layer with Amazon API Gateway
  • Symfony Messenger Integration: CQRS and Async Message Processing
    • Installing Symfony Messenger
    • Dispatching a Resource through the Message Bus
    • Registering a Message Handler
    • Accessing to the Data Returned by the Handler
    • Detecting Removals
  • Using Data Transfer Objects (DTOs)
    • Specifying an Input or an Output Class
    • Disabling the Input or the Output
    • Creating a Service-Oriented endpoint
  • Pushing Related Resources Using HTTP/2
  • Handling File Upload
    • Installing VichUploaderBundle
    • Configuring the Entity Receiving the Uploaded File
    • Handling File Upload
    • Making a Request to the /media_objects Endpoint
    • Linking a MediaObject Resource to Another Resource
  • Overriding Default Order
  • Errors Handling
    • Converting PHP Exceptions to HTTP Errors
  • Using External Vocabularies
  • Operation Path Naming
    • Configuration
    • Create a Custom Operation Path Resolver
      • Defining the Operation Path Resolver
      • Registering the Service
      • Configure It
  • Extending JSON-LD context
  • Accept application/x-www-form-urlencoded Form Data
    • Create your DeserializeListener Decorator
    • Creating the Service Definition
  • Identifiers
    • Custom identifier normalizer
    • Supported identifiers
  • JWT Authentication
    • Installing LexikJWTAuthenticationBundle
    • Documenting the Authentication Mechanism with Swagger/Open API
      • Configuring API Platform
      • Adding a New API Key
    • Testing with Behat
  • AngularJS Integration
    • Restangular
    • ng-admin
  • FOSUserBundle Integration
    • Installing the Bundle
    • Enabling the Bridge
    • Creating a User Entity with Serialization Groups
  • NelmioApiDocBundle Integration
  • Configuration

The Schema Generator Component

  • The schema generator
    • What is Schema.org?
    • Why use Schema.org data to generate a PHP model?
      • Don't Reinvent The Wheel
      • Improve SEO and user experience
      • Be ready for the future
    • Documentation
  • Getting Started
    • Installation
    • Model Scaffolding
      • Going Further
    • Cardinality Extraction
  • Configuration
    • Customizing PHP Namespaces
    • Forcing a Field Range
    • Forcing a Field Cardinality
    • Forcing a Relation Table Name
    • Forcing (or Disabling) a Class Parent
    • Forcing a Class to be Abstract
    • Forcing a Nullable Property
    • Forcing a Unique Property
    • Making a Property Read Only
    • Making a Property Write Only
    • Forcing a Property to be in a Serialization Group
    • Forcing an Embeddable Class to be Embedded
    • Author PHPDoc
    • Disabling Generators and Creating Custom Ones
    • Skipping Accessor Method Generation
    • Disabling the id Generator
    • Generating UUIDs
    • User submitted UUIDs
    • Generating Custom IDs
    • Disabling Usage of Doctrine Collection
    • Changing the Field Visibility
    • Generating @Assert\Type Annotations
    • Forcing Doctrine Inheritance Mapping Annotation
    • Interfaces and Doctrine Resolve Target Entity Listener
    • Custom Schemas
    • Checking GoodRelation Compatibility
    • PHP File Header
    • Full Configuration Reference

The Admin Component

  • The API Platform Admin
    • Features
  • Getting Started
    • Installation
    • Creating the Admin
    • Customizing the Admin
      • Using Custom Components
      • Managing Files and Images
      • Using a Custom Validation Function or Inject Custom Props
      • Using the Hydra Data Provider Directly with react-admin
  • Authentication Support
  • Handling Relations to Collections
    • Customizing a Property
    • Customizing an Icon
    • Using an Autocomplete Input for Relations

The Client Generator Component

  • The API Platform Client Generator
    • Features
  • React Generator
    • Install
    • Generating a Progressive Web App
    • Screenshots
  • Vue.js Generator
  • React Native generator
    • Install
    • Generating a Native App
    • Screenshots in iOS Simulator
  • Troubleshooting

Deployment

  • Deploying API Platform Applications
  • Deploying to a Kubernetes Cluster
    • Preparing Your Cluster and Your Local Machine
    • Creating and Publishing the Docker Images
    • Deploying
    • Initializing the Database
    • Tiller RBAC Issue
  • Deploying an API Platform App on Heroku
  • Implement Traefik Into API Platform Dockerized
    • Basic Implementation
    • Known Issues

Extra

  • The Release Process
  • API Platform's Philosophy
  • Troubleshooting
    • Using Docker
      • With Docker Toolbox on Windows
      • Error starting userland proxy
    • Using API Platform and JMS Serializer in the same project
    • "upstream sent too big header while reading response header from upstream" 502 Error
  • Contribution guides
  • Contributor Code of Conduct
spidey

Copyright © 2019 Kévin Dunglas

Supported by Les-Tilleuls.coop

Code licensed under MIT, documentation under CC BY 3.0.

spidey
test1
Home
docs
DistributionAPI componentSchema componentAdmin componentScaffolding componentDeployment
Demo
News
Support