MongoDB (Database service)

Use a framework 

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

For more implementation ideas, consult a template.

Supported versions 

Enterprise edition 

Premium feature

MongoDB Enterprise isn't included in any Platform.sh plan. You need to add it separately at an additional cost. To add MongoDB Enterprise, contact Sales.

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

Deprecated versions 

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 at some point in the future, so you should migrate to one of the supported versions.

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

Legacy edition 

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 

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 at some point in the future, so you should migrate to one of the supported versions.

Grid
  • 3.6
  • 3.4
  • 3.2
  • 3.0

Relationship 

The format exposed in the $PLATFORM_RELATIONSHIPS environment variable:

{
    "username": "main",
    "scheme": "mongodb",
    "service": "mongodb36",
    "ip": "169.254.150.147",
    "hostname": "blbczy5frqpkt2sfkj2w3zk72q.mongodb36.service._.eu-3.platformsh.site",
    "cluster": "rjify4yjcwxaa-master-7rqtwti",
    "host": "mongodb.internal",
    "rel": "mongodb",
    "query": {
        "is_master": true
    },
    "path": "main",
    "password": "main",
    "type": "mongodb:3.6",
    "port": 27017
}

Usage example 

Enterprise edition example 

1. Configure the service 

Use the mongodb-enterprise type to define the service:

.platform/services.yaml
<SERVICE_NAME>:
    type: mongodb-enterprise:<VERSION>
    disk: 512

Note that if you later change the name, it’s treated as an entirely new service. This removes all data from your service. Always backup your data before changing the service.

2. Add the relationship 

Use the mongodb endpoint to define the relationship:

.platform.app.yaml
relationships:
    <RELATIONSHIP_NAME>: "<SERVICE_NAME>:mongodb"

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, but it’s best if they’re distinct.

For PHP, enable the extension for the service:

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

Example Configuration 

Service definition

.platform/services.yaml
dbmongo:
    type: mongodb-enterprise:5.0
    disk: 512

App configuration

.platform.app.yaml
relationships:
    mongodatabase: "dbmongo:mongodb"

# If using PHP
runtime:
    extensions:
        - mongodb

Legacy edition example 

1. Configure the service 

Use the mongodb type to define the service:

.platform/services.yaml
<SERVICE_NAME>:
    type: mongodb:<VERSION>
    disk: 512

Note that if you later change the name, it’s treated as an entirely new service. This removes all data from your service. Always backup your data before changing the service.

2. Add the relationship 

Use the mongodb endpoint to define the relationship:

.platform.app.yaml
relationships:
    <RELATIONSHIP_NAME>: "<SERVICE_NAME>:mongodb"

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, but it’s best if they’re distinct.

For PHP, enable the extension for the service:

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

Example Configuration 

Service definition

.platform/services.yaml
dbmongo:
    type: mongodb:3.6
    disk: 512

App configuration

.platform.app.yaml
relationships:
    mongodatabase: "dbmongo:mongodb"

# If using PHP
runtime:
    extensions:
        - mongodb

Use in app 

Then use the service in your app with a configuration file like the following:

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 

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

mongo HOST

With the example value, that would be the following:

mongo mongodb.internal

Exporting data 

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: database
SSH tunnel opened on port 30001 to relationship: redis

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 

To upgrade to 3.6 from a version earlier than 3.4, you must successively upgrade major releases until you have upgraded to 3.4. For example, if you are running a 3.0 image, you must upgrade first to 3.2 and then upgrade to 3.4 before you can upgrade to 3.6.

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