MongoDB (Database service)

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

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

Supported versions

  • 3.0
  • 3.2
  • 3.4
  • 3.6

note

Downgrades of MongoDB are not supported. MongoDB will update its own datafiles to a new version automatically but cannot downgrade them. If you want to experiment with a later version without committing to it use a non-master environment.

Relationship

The format exposed in the $PLATFORM_RELATIONSHIPS environment variable:

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

Usage example

In your .platform/services.yaml:

dbmongo:
    type: mongodb:3.6
    disk: 512

The minimum disk size for MongoDB is 512 (MB).

relationships:
    mongodatabase: "dbmongo:mongodb"

For PHP, in your .platform.app.yaml add:

runtime:
    extensions:
        - mongodb

(Before PHP 7, use mongo instead.)

You can then use the service in a configuration file of your application with something like:

Go
Java
Node.js
PHP
Python
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(myDoc.toJson()).append('\n');
        logger.append(collection.deleteOne(eq("_id", doc.get("_id"))));
        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;

    var client = await MongoClient.connect(config.formattedCredentials('mongodb', 'mongodb'));

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

    let 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.insert(documents, {w: 1});

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

    let output = '';

    output += `<table>
<thead>
<tr><th>Name</th><th>Rank</th></tr>
</thead>
<tbody>`;

    Object.keys(result).forEach((key) => {
        output += `<tr><td>${result[key].name}</td><td>${result[key].rank}</td></tr>\n`;
    });

    output += `</tbody>\n</table>\n`;

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

    return output;
};
<?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

Exporting data

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

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

platform tunnel:open

That will open an SSH tunnel to all services on your current environment, and produce output something 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 will also need to obtain the user, password, and database name from the relationships array, as above.

Then, simply 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 please 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, please see Release Notes for MongoDB.