Platform.sh User Documentation

MongoDB (Database service)

Sign up for Upsun

Get your free trial by clicking the link below.

Get your Upsun free trial

MongoDB is a cross-platform, document-oriented database.

For more information on using MongoDB, see MongoDB’s own documentation.

Use a framework Anchor to this heading

If you use one of the following frameworks, follow its guide:

For more implementation ideas, consult a template.

Supported versions Anchor to this heading

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.

Enterprise edition Anchor to this heading

Grid Dedicated Gen 3 Dedicated Gen 2
  • 7.0
  • 6.0
  • 5.0
  • 4.4
  • 4.2
None available
  • 6.0
  • 5.0
  • 4.4
  • 4.2

Deprecated versions Anchor to this heading

The following versions are deprecated. They’re available, but they aren’t receiving security updates from upstream and aren’t guaranteed to work. They’ll be removed in the future, so migrate to one of the supported versions.

Grid Dedicated Gen 3 Dedicated Gen 2
  • 4.0
None available
  • 4.0

Legacy edition Anchor to this heading

Previous non-Enterprise versions are available in your projects (and are listed below), but they’re at their end of life and are no longer receiving security updates from upstream.

Deprecated versions Anchor to this heading

The following versions are deprecated. They’re available, but they aren’t receiving security updates from upstream and aren’t guaranteed to work. They’ll be removed in the future, so migrate to one of the supported versions.

  • 4.0.3
  • 3.6
  • 3.4
  • 3.2
  • 3.0

Relationship reference Anchor to this heading

Example information available through the PLATFORM_RELATIONSHIPS environment variable or by running platform relationships.

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the PLATFORM_RELATIONSHIPS environment variable directly rather than hard coding any values.

{
    "username": "main",
    "scheme": "mongodb",
    "service": "mongodb",
    "ip": "123.456.78.90",
    "hostname": "azertyuiopqsdfghjklm.mongodb.service._.eu-1.platformsh.site",
    "cluster": "azertyuiop-main-7rqtwti",
    "host": "mongodb.internal",
    "rel": "mongodb",
    "query": {
        "is_master": true
    },
    "path": "main",
    "password": null,
    "type": "mongodb-enterprise:7.0",
    "port": 27017
}

Usage example Anchor to this heading

Enterprise edition example Anchor to this heading

1. Configure the service Anchor to this heading

To define the service, use the mongodb-enterprise type:

.platform/services.yaml
# The name of the service container. Must be unique within a project.
<SERVICE_NAME>:
    type: mongodb-enterprise:<VERSION>
    disk: 512

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

2. Add the relationship Anchor to this heading

To define the relationship, use the following configuration:

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
    <SERVICE_NAME>: 

You can define <SERVICE_NAME> as you like, so long as it’s unique between all defined services and matches in both the application and services configuration.

The example above leverages default endpoint configuration for relationships. That is, it uses default endpoints behind-the-scenes, providing a relationship (the network address a service is accessible from) that is identical to the name of that service.

Depending on your needs, instead of default endpoint configuration, you can use explicit endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <RELATIONSHIP_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

For PHP, enable the extension for the service:

.platform.app.yaml
# PHP extensions.
runtime:
    extensions:
        - mongodb

Example Configuration Anchor to this heading

Service definition Anchor to this heading

.platform/services.yaml
# The name of the service container. Must be unique within a project.
mongodb-enterprise:
    type: mongodb-enterprise:7.0
    disk: 512

App configuration Anchor to this heading

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
    mongodb-enterprise: 

Legacy edition example Anchor to this heading

1. Configure the service Anchor to this heading

To define the service, use the mongodb type:

.platform/services.yaml
# The name of the service container. Must be unique within a project.
<SERVICE_NAME>:
    type: mongodb:<VERSION>
    disk: 512

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

2. Add the relationship Anchor to this heading

To define the relationship, use the following configuration:

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
    <SERVICE_NAME>: 

You can define <SERVICE_NAME> as you like, so long as it’s unique between all defined services and matches in both the application and services configuration.

The example above leverages default endpoint configuration for relationships. That is, it uses default endpoints behind-the-scenes, providing a relationship (the network address a service is accessible from) that is identical to the name of that service.

Depending on your needs, instead of default endpoint configuration, you can use explicit endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <RELATIONSHIP_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

For PHP, enable the extension for the service:

.platform.app.yaml
# PHP extensions.
runtime:
    extensions:
        - mongodb

Example Configuration Anchor to this heading

Service definition Anchor to this heading

.platform/services.yaml
# The name of the service container. Must be unique within a project.
mongodb:
    type: mongodb:3.6
    disk: 512

App configuration Anchor to this heading

.platform.app.yaml
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
    mongodb: 

Use in app Anchor to this heading

To use the configured service in your app, add a configuration file similar to the following to your project.

package examples

import (
	"context"
	"fmt"
	psh "github.com/platformsh/config-reader-go/v2"
	mongoPsh "github.com/platformsh/config-reader-go/v2/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

func UsageExampleMongoDB() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to the Solr service.
	credentials, err := config.Credentials("mongodb")
	checkErr(err)

	// Retrieve the formatted credentials for mongo-driver.
	formatted, err := mongoPsh.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to MongoDB using the formatted credentials.
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(formatted))
	checkErr(err)

	// Create a new collection.
	collection := client.Database("main").Collection("starwars")

	// Clean up after ourselves.
	err = collection.Drop(context.Background())
	checkErr(err)

	// Create an entry.
	res, err := collection.InsertOne(ctx, bson.M{"name": "Rey", "occupation": "Jedi"})
	checkErr(err)

	id := res.InsertedID

	// Read it back.
	cursor, err := collection.Find(context.Background(), bson.M{"_id": id})
	checkErr(err)

	var name string
	var occupation string

	for cursor.Next(context.Background()) {
		document := struct {
			Name       string
			Occupation string
		}{}
		err := cursor.Decode(&document)
		checkErr(err)

		name = document.Name
		occupation = document.Occupation
	}

	return fmt.Sprintf("Found %s (%s)", name, occupation)
}
package sh.platform.languages.sample;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import sh.platform.config.Config;
import sh.platform.config.MongoDB;

import java.util.function.Supplier;

import static com.mongodb.client.model.Filters.eq;

public class MongoDBSample implements Supplier<String> {

    @Override
    public String get() {
        StringBuilder logger = new StringBuilder();

        // Create a new config object to ease reading the Platform.sh environment variables.
        // You can alternatively use getenv() yourself.
        Config config = new Config();

        // The 'database' relationship is generally the name of primary database of an application.
        // It could be anything, though, as in the case here here where it's called "mongodb".
        MongoDB database = config.getCredential("mongodb", MongoDB::new);
        MongoClient mongoClient = database.get();
        final MongoDatabase mongoDatabase = mongoClient.getDatabase(database.getDatabase());
        MongoCollection<Document> collection = mongoDatabase.getCollection("scientist");
        Document doc = new Document("name", "Ada Lovelace")
                .append("city", "London");

        collection.insertOne(doc);
        Document myDoc = collection.find(eq("_id", doc.get("_id"))).first();
        logger.append("<p>");
        logger.append(myDoc.toJson()).append('\n');
        logger.append(collection.deleteOne(eq("_id", doc.get("_id"))));
        logger.append("</p>");
        return logger.toString();
    }
}
const mongodb = require("mongodb");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("mongodb");
    const MongoClient = mongodb.MongoClient;

    const client = await MongoClient.connect(
        config.formattedCredentials("mongodb", "mongodb")
    );

    const db = client.db(credentials["path"]);

    const collection = db.collection("startrek");

    const documents = [
        { name: "James Kirk", rank: "Admiral" },
        { name: "Jean-Luc Picard", rank: "Captain" },
        { name: "Benjamin Sisko", rank: "Prophet" },
        { name: "Katheryn Janeway", rank: "Captain" },
    ];

    await collection.insertMany(documents, { w: 1 });

    const result = await collection.find({ rank: "Captain" }).toArray();

    const outputRows = Object.values(result)
        .map(({ name, rank }) => `<tr><td>${name}</td><td>${rank}</td></tr>\n`)
        .join("\n");

    // Clean up after ourselves.
    collection.deleteMany();

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>Rank</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};
<?php

declare(strict_types=1);

use Platformsh\ConfigReader\Config;
use MongoDB\Client;

// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();

// The 'database' relationship is generally the name of primary database of an application.
// It could be anything, though, as in the case here here where it's called "mongodb".
$credentials = $config->credentials('mongodb');

try {

    $server = sprintf('%s://%s:%s@%s:%d/%s',
        $credentials['scheme'],
        $credentials['username'],
        $credentials['password'],
        $credentials['host'],
        $credentials['port'],
        $credentials['path']
    );

    $client = new Client($server);
    $collection = $client->main->starwars;

    $result = $collection->insertOne([
        'name' => 'Rey',
        'occupation' => 'Jedi',
    ]);

    $id = $result->getInsertedId();

    $document = $collection->findOne([
        '_id' => $id,
    ]);

    // Clean up after ourselves.
    $collection->drop();

    printf("Found %s (%s)<br />\n", $document->name, $document->occupation);

} catch (\Exception $e) {
    print $e->getMessage();
}
from pymongo import MongoClient
from platformshconfig import Config


def usage_example():

    # Create a new Config object to ease reading the Platform.sh environment variables.
    # You can alternatively use os.environ yourself.
    config = Config()

    # The 'database' relationship is generally the name of primary SQL database of an application.
    # It could be anything, though, as in the case here here where it's called "mongodb".
    credentials = config.credentials('mongodb')

    try:
        formatted = config.formatted_credentials('mongodb', 'pymongo')

        server = '{0}://{1}:{2}@{3}'.format(
            credentials['scheme'],
            credentials['username'],
            credentials['password'],
            formatted
        )

        client = MongoClient(server)

        collection = client.main.starwars

        post = {
            "name": "Rey",
            "occupation": "Jedi"
        }

        post_id = collection.insert_one(post).inserted_id

        document = collection.find_one(
            {"_id": post_id}
        )

        # Clean up after ourselves.
        collection.drop()

        return 'Found {0} ({1})<br />'.format(document['name'], document['occupation'])

    except Exception as e:
        return e

Access the service directly Anchor to this heading

You can access MongoDB from you app container via SSH. Get the host from your relationship. Then run the following command:

mongo MONGODB_HOST

With the example value, that would be the following:

mongo mongodb.internal

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the PLATFORM_RELATIONSHIPS environment variable directly rather than hard coding any values.

Exporting data Anchor to this heading

The most straightforward way to export data from a MongoDB database is to open an SSH tunnel to it and export the data directly using MongoDB’s tools.

First, open an SSH tunnel with the Platform.sh CLI:

platform tunnel:open

That opens an SSH tunnel to all services on your current environment and produce output like the following:

SSH tunnel opened on port 30000 to relationship: mongodb

The port may vary in your case. You also need to obtain the user, password, and database name from the relationships array, as above.

Then, connect to that port locally using mongodump (or your favorite MongoDB tools) to export all data in that server:

mongodump --port 30000 -u main -p main --authenticationDatabase main --db main

(If necessary, vary the -u, -p, --authenticationDatabase and --db flags.)

As with any other shell command it can be piped to another command to compress the output or redirect it to a specific file.

For further references, see the official mongodump documentation.

Upgrading Anchor to this heading

To upgrade to 6.0 from a version earlier than 5.0, you must successively upgrade major releases until you have upgraded to 5.0. For example, if you are running a 4.2 image, you must upgrade first to 4.4 and then upgrade to 5.0 before you can upgrade to 6.0.

For more details on upgrading and how to handle potential application backward compatibility issues, see the MongoDB release notes.

Downgrading isn’t supported. If you want, for whatever reason, to downgrade you should create a mongodump, remove the service, recreate the service, and import your dump.

Is this page helpful?