MongoDB Classic Retirement
All Compose MongoDB Classic databases must be migrated to a current IBM/Compose MongoDB offering by June 30, 2020. Read more here: https://help.compose.com/docs/mongodb-classic-retirement
To connect directly to your database from the mongo console, be sure you have mongodb installed locally. If you need help with that, check out MongoDB's installation instructions.
Simply connect your local mongo console using your command line snippet, which will look something like this:


The Connection info panel.
The connection string is what you'd use when you're connecting your application.
Connecting Your Application
We're happy to provide assistance with your MongoDB installation, however for in depth application and driver support, check out the appropriate documentation and communities for your specific language and the driver that your application is using. Having said that, we've taken some of our experiences with common languages and drivers and written tutorials for them:
If you're looking for languages that are not listed here, please see the 10Gen MongoDB Driver List.
C# / .NET, MongoDB and Compose
This guide assumes that you have already downloaded and installed the MongoDB C# driver for your project.
If you have not done so, you can find the installer at: http://github.com/mongodb/mongo-csharp-driver/downloads.
Once installation is complete, you will be able to reference the MongoDriver and MongoBSON DLLs within Visual Studio.
Create a New Project###
To begin, letʼs create a new project in Visual Studio. I chose to use ASP.NET MVC 2 Web Application in this example. (The examples given can be easily ported to WebForms if necessary.)


The New Project pane in Visual Studio.
Add References###
Now we will need to reference the MongoDriver and MongoBSON DLLs so that we can connect to our MongoDB database. The C# driver installer added these two DLLs to the .NET tab of your reference window.
With these references added, we are now able to connect and query our Compose database with just a few lines of code.


Adding a reference from the .NET list.
Add Connection Information###
Next, let's set up our connection string with our database information by adding a new connection string in our application's web.config file. The entry should look similar to this:
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="Compose"
connectionString="your mongo uri"/>
</connectionStrings>
Of course, your mongo uri should be replaced with the actual Compose URI that is provided to you in the web interface. You can get this by doing the following:
- Log into Compose
- Click on the port number of the database you want to connect to
- Copy or note the URI that is provided.
You will just need the root URI, so you can choose any database you would like.
Setting up your Model and Controller###
Now, let's create a model to hold our documents. The database used in this example is a collection of developers with basic information, so we will create a Data Transformation Object (DTO) to store these properties and return a generic list of these DTOs in our model.
Create a DTO directory under the Model directory for our DeveloperDTO.cs file.
namespace mongodb_csharp.Models.DTO
{
public class DeveloperDTO
{
public BsonObjectId id { get; set; }
public string name { get; set; }
public string languages { get; set; }
public string company { get; set; }
}
}
Add our DeveloperModel.cs to the Models directory. Make sure you include a using clause for the DTO directory.
using System.Collections.Generic;
using mongodb_csharp.Models.DTO;
namespace mongodb_csharp.Models
{
public class DeveloperModel
{
public IList<DeveloperDTO> developers { get; set; }
}
}
Now let's create our DeveloperController.
In this example, let's name it DeveloperController. You can uncheck the box for "Add action methods for Create, Update and Delete Scenarios" as we won't be covering this functionality in the Getting Started guide.
Open your newly created controller and add your using clauses. At a minimum, you should have the following.
Notice the highlighted line where we are declare a private MongoDatabase
object and instantiating it in our constructor.
using System.Linq;
using System.Web.Mvc;
using System.Configuration;
using MongoDB.Driver;
using mongodb_csharp.Models;
using cimpose_csharp.Models.DTO;
namespace mongodb_csharp.Controllers
{
public class DeveloperController : Controller
{
readonly MongoDatabase mongo_db;
public DeveloperController()
{
mongo_db = retreive_mongodb_db();
}
public ActionResult Index()
{
var model = new DeveloperModel();
var developers_collection = mongo_db.GetCollection("developers").FindAll().AsEnumerable();
model.developers = (from developer in developers_collection
select new DeveloperDTO
{
id = developer["_id"].AsObjectId,
name = developer["name"].AsString,
languages = developer["languages"].AsBsonArray.ToString(),
company = developer["company"].AsString
}).ToList();
return View(model);
}
static MongoDatabase retreive_mongodb_db()
{
return MongoServer.Create(
ConfigurationManager.ConnectionStrings["Compose"].ConnectionString)
.GetDatabase("t2");
}
}
}
As you can see, I broke the database call into a separate method, which is listed below. Here, we utilize the MongoServer.Create
method to initialize a connection to our Compose server using our connection string from our web.config. Now we can call GetDatabase
to get our MongoDatabase
instance.
In this case, my database name is t2.
For more information on these methods, take a look at the CSharp Driver Tutorial.
static MongoDatabase retreive_mongodb_db()
{
return MongoServer.Create(
ConfigurationManager.ConnectionStrings["Compose"].ConnectionString)
.GetDatabase("t2");
}
Add an Index
method to our DeveloperController
Now that our connections are set up, let's add a method to our DeveloperController.cs that will assist in delivering the database content to our soon-to-be created view.
public ActionResult Index()
{
var model = new DeveloperModel();
var developers_collection = mongo_db.GetCollection("developers").FindAll().AsEnumerable();
model.developers = (from developer in developers_collection
select new DeveloperDTO
{
id = developer["_id"].AsObjectId,
name = developer["name"].AsString,
languages = developer["languages"].AsBsonArray.ToString(),
company = developer["company"].AsString
}).ToList();
return View(model);
}
Success!
We now have a connection to our database and a method to deliver the content to our view. All we need to do now is hydrate our model and pass it to the view.
Viewing Data
In this example, we simply iterate over our developers and print them to the screen. Create a Developer
folder in the Views directory and add a new .aspx file called Index.aspx
. Add the code below and youʼre all set.
<%%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<mongodb_csharp.Models.DeveloperModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Developers</h2>
<ul>
<%% foreach(var developer in Model.developers) { %>
<li><%%= developer.name %> works for <%%= developer.company %> and is proficient in <%%= developer.languages %></li>
<%% } %>
</ul>
</asp:Content>
For more information, please check out the MongoDB C# Driver API documentation.
Go / Golang, MongoDB and Compose
As in the other examples, this document assumes an environmental variable called MONGOHQ_URL
with your Compose Connection string. To set this variable, execute the following in the shell:
export MONGODB_URL="mongodb://user:[email protected]/db_name"
The mgo driver is the standard mongo driver for go, and can be installed by:
go get gopkg.in/mgo.v2
A code sample:
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"os"
)
type msg struct {
Id bson.ObjectId `bson:"_id"`
Msg string `bson:"msg"`
Count int `bson:"count"`
}
func main() {
uri := os.Getenv("MONGODB_URL")
if uri == "" {
fmt.Println("no connection string provided")
os.Exit(1)
}
sess, err := mgo.Dial(uri)
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
os.Exit(1)
}
defer sess.Close()
sess.SetSafe(&mgo.Safe{})
collection := sess.DB("test").C("foo")
doc := msg{Id: bson.NewObjectId(), Msg: "Hello from go"}
err = collection.Insert(doc)
if err != nil {
fmt.Printf("Can't insert document: %v\n", err)
os.Exit(1)
}
err = collection.Update(bson.M{"_id": doc.Id}, bson.M{"$inc": bson.M{"count": 1}})
if err != nil {
fmt.Printf("Can't update document %v\n", err)
os.Exit(1)
}
var updatedmsg msg
err = sess.DB("test").C("foo").Find(bson.M{}).One(&updatedmsg)
if err != nil {
fmt.Printf("got an error finding a doc %v\n")
os.Exit(1)
}
fmt.Printf("Found document: %+v\n", updatedmsg)
}
For further reference, mgo has great documentation, which is available at http://labix.org/mgo.
Node.js / Native
Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGOHQ_URL
, like this:
var MONGODB_URL="mongodb://user:[email protected]:port_name/db_name"
This code uses the node-mongodb-native driver, though in production you may want something a little less... nesty. Like all good Node packages, you can get it via NPM.
npm install mongodb
Connecting with Node.js (Javascript)
// npm install mongodb
var mongodb = require('mongodb')
, MongoClient = mongodb.MongoClient
MongoClient.connect(process.env.MONGODB_URL, function(err, db) {
// operate on the collection named "test"
var collection = db.collection('test')
// remove all records in collection (if any)
console.log('removing documents...')
collection.remove(function(err, result) {
if (err) {
return console.error(err)
}
console.log('collection cleared!')
// insert two documents
console.log('inserting new documents...')
collection.insert([{name: 'tester'}, {name: 'coder'}], function(err,
docs) {
if (err) {
return console.error(err)
}
console.log('just inserted ', docs.length, ' new documents!')
collection.find({}).toArray(function(err, docs) {
if (err) {
return console.error(err)
}
docs.forEach(function(doc) {
console.log('found document: ', doc)
})
})
})
})
})
Connecting with Node.js (Coffeescript)
# npm install mongodb
mongodb = require 'mongodb'
url = require 'url'
log = console.log
connection_uri = url.parse(process.env.COMPOSE_URL)
db_name = connection_uri.pathname.replace(/^\//, '')
mongodb.Db.connect process.env.COMPOSE_URL, (error, client)->
throw error if error
client.collectionNames (error, names)->
throw error if error
# output all collection names
log "Collections"
log "==========="
last_collection = null
for col_data in names
col_name = col_data.name.replace("#{db_name}.", '')
log col_name
last_collection = col_name
collection = new mongodb.Collection(client, last_collection)
log "\nDocuments in #{last_collection}"
documents = collection.find({}, limit : 5)
# output a count of all documents found
documents.count (error, count)->
log " #{count} documents(s) found"
log "===================="
# output the first 5 documents
documents.toArray (error, docs)->
throw error if error
for doc in docs then log doc
# close the connection
client.close()
That should do the trick!
Mongoose, Node and Compose
Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGOHQ_URL
, like this:
var MONGODB_URL="mongodb://user:[email protected]:port_name/db_name"
This code uses the mongoose driver. Like all good Node packages, you can get it via NPM.
npm install mongoose
Connecting with Mongoose (Javascript)
var SuperHero, hero, mongoose, _;
mongoose = require("mongoose");
_ = require("underscore");
mongoose.connect(process.env.MONGODB_URL);
SuperHero = mongoose.model('SuperHero', { name: "string" });
hero = new SuperHero({
name: "Superman"
});
hero.save(function(err) {
if (err) {
return console.log("kryptonite");
} else {
return console.log("Up, up, and away!");
}
});
SuperHero.find({}, function(err, documents) {
return console.log(documents[0]);
});
Connecting with Mongoose (Coffeescript)
mongoose = require("mongoose")
_ = require("underscore")
mongoose.connect(process.env.COMPOSE_URL)
SuperHeroSchema = new mongoose.Schema({
name: { type: String }
})
SuperHero = mongoose.model 'SuperHero', SuperHeroSchema
hero = new SuperHero name: "Superman"
hero.save (err) ->
if (err)
console.log("kryptonite")
else
console.log("Up, up, and away!")
# process.exit(0)
SuperHero.find {}, (err, documents) ->
console.log documents[0]
Great!
R, MongoDB and Compose
The rmongodb driver is the standard mongodb driver for R, and can be installed by launching the Package Installer from within the R Environment, and installing the rmongodb package
The following can be run directly within the R Environment. take care to use the correct user/password, host, port. The defaults below will likely not work.
library(rmongodb)
# your connection details will likely differ from these defaults
host <- "dharma.compose.io:10200"
username <- "myuser"
password <- "mypassword"
db <- "testdatabase"
#connect to mongo
#the create function has the following signature
#mongo.create(host="127.0.0.1", name="", username="", password="", db="admin", timeout=0L)
mongo <- mongo.create(host=host , db=db, username=username, password=password)
# lets create a string that points to our namespace
# the database we're working with is "testdatabase", and the collection is "example"
collection <- "example"
namespace <- paste(db, collection, sep=".") "testdabase.example"
#get a list of collections within our namespace
mongo.get.database.collections(mongo, db)
# find the number of documents in 'exampleCollection' collection in the the 'testdatabase' database
mongo.count(mongo, namespace, mongo.bson.empty())
#lets create a document to insert
b <- mongo.bson.from.list(list(platform="Compose", language="R", number=1))
#insert the document into our namespace
ok <- mongo.insert(mongo, namespace, b)
# lets insert a few documents
for (i in 2:50 ) {
b <- mongo.bson.from.list(list(platform="Compose", language="R", number=i))
mongo.insert(mongo, namespace, b)
}
# build a query to find all "language: R"
buf <- mongo.bson.buffer.create()
mongo.bson.buffer.append(buf, "language", "R")
query <- mongo.bson.from.buffer(buf)
# get the count
count <- mongo.count(mongo, namespace, query)
#and bring them back into a list
numbers <- list()
cursor <- mongo.find(mongo, namespace, query)
while (mongo.cursor.next(cursor)) {
val <- mongo.cursor.value(cursor)
numbers[[length(numbers)+1]] <- mongo.bson.value(val, "number")
}
For further reference, rmongodb documentation is available at http://cnub.org/doc/rmongodb.pdf.
Ruby, MongoDB and Compose
Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGODB_URL
, like this:
MONGODB_URL="mongodb://user:[email protected]/db_name"
If you are using Ruby (along with frameworks like Ruby on Rails, Sinatra, etc.), you can start out by installing the mongo
(2.x) gem. It should go without saying, but you will need RubyGems.
# gem install mongo
require 'rubygems' # if less than Ruby 1.9
require 'mongo'
def client
@client ||= Mongo::Client.new(ENV['MONGODB_URL'])
end
db = client.database
puts "Collections"
puts "==========="
collections = db.collection_names
puts collections # ["coll1", "coll2", ...]
coll = client[collections.last]
# find show 5
query = coll.find().limit(5)
puts "\nDocuments in #{coll.name}"
puts " #{query.count} documents(s) found"
puts "=========================="
query.each{ |doc| puts doc.to_json }
You're in!
Python, MongoDB and Compose
Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGODB_URL
, like this:
MONGODB_URL="mongodb://user:[email protected]/database_name"
If you are using Python, you can start out by installing PyMongo.
import os
import datetime
import pymongo
from pymongo import MongoClient
# Grab our connection information from the MONGODB_URL environment variable
# (mongodb://linus.compose.io:10045 -u username -pmy_password)
MONGOHQ_URL = os.environ.get('MONGODB_URL')
#connection = Connection(MONGOHQ_URL)
client = MongoClient(MONGOHQ_URL)
# Specify the database
db = client.mytestdatabase
# Print a list of collections
print db.collection_names()
# Specify the collection, in this case 'monsters'
collection = db.monsters
# Get a count of the documents in this collection
count = collection.count()
print "The number of documents you have in this collection is:", count
# Create a document for a monster
monster = {"name": "Dracula",
"occupation": "Blood Sucker",
"tags": ["vampire", "teeth", "bat"],
"date": datetime.datetime.utcnow()
}
# Insert the monster document into the monsters collection
monster_id = collection.insert(monster)
# Print out our monster documents
for monster in collection.find():
print monster
# Query for a particular monster
print collection.find_one({"name": "Dracula"})
And then, you should be on your way.
PHP, MongoDB, and Compose
Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGODB_URL
, like this:
export MONGODB_URL="mongodb://user:[email protected]/db_name"
This originally began as a Gist from Larry Hitchon of AppFog. We made some improvements and made it Compose-centric. It's a pretty straightforward driver. If you don't have PECL, you should install PECL.
sudo pecl install mongo
And then, to the code sample:
<!-- PHP Mongo Docs: http://php.net/manual/en/class.mongodb.php -->
<!-- PHP Mongo Docs: http://php.net/manual/en/class.mongodb.php -->
<html>
<body>
<h1>Compose Test</h1>
<?php
try {
// connect to Compose assuming your MONGODB_URL environment
// variable contains the connection string
$connection_url = getenv("MONGODB_URL");
// create the mongo connection object
$m = new MongoClient($connection_url);
// extract the DB name from the connection path
$url = parse_url($connection_url);
$db_name = preg_replace('/\/(.*)/', '$1', $url['path']);
// use the database we connected to
$db = $m->selectDB($db_name);
echo "<h2>Collections</h2>";
echo "<ul>";
// print out list of collections
$cursor = $db->listCollections();
$collection_name = "";
foreach( $cursor as $doc ) {
echo "<li>" . $doc->getName() . "</li>";
$collection_name = $doc->getName();
}
echo "</ul>";
// print out last collection
if ( $collection_name != "" ) {
$collection = $db->selectCollection($collection_name);
echo "<h2>Documents in ${collection_name}</h2>";
// only print out the first 5 docs
$cursor = $collection->find();
$cursor->limit(5);
echo $cursor->count() . ' document(s) found. <br/>';
foreach( $cursor as $doc ) {
echo "<pre>";
var_dump($doc);
echo "</pre>";
}
}
// disconnect from server
$m->close();
} catch ( MongoConnectionException $e ) {
die('Error connecting to MongoDB server');
} catch ( MongoException $e ) {
die('Mongo Error: ' . $e->getMessage());
} catch ( Exception $e ) {
die('Error: ' . $e->getMessage());
}
?>
</body>
</html>
That should get you well on your way.
Updated 11 months ago