Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

WARNING: You are browsing the documentation for Symfony 4.0 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database

4.0 version
Maintained Unmaintained

How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database

The default Symfony session storage writes the session information to files. Some medium to large websites use a NoSQL database called MongoDB to store the session values instead of files, because databases are easier to use and scale in a multi-webserver environment.

Symfony has a built-in solution for NoSQL database session storage called Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler. To use this, you will need to:

  1. Register a MongoDbSessionHandler service;
  2. Configure this under framework.session.handler_id configuration.

To see how to configure a similar handler, see How to Use PdoSessionHandler to Store Sessions in the Database.

Setting Up the MongoDB Collection

You do not need to do anything to initialize your session collection. However, you may want to add an index to improve garbage collection performance. From the MongoDB shell:

use session_db
db.session.ensureIndex( { "expires_at": 1 }, { expireAfterSeconds: 0 } )

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.