Skip to content

Instantly share code, notes, and snippets.

@louismrose
Created December 3, 2012 21:11
Show Gist options
  • Save louismrose/4198081 to your computer and use it in GitHub Desktop.
Save louismrose/4198081 to your computer and use it in GitHub Desktop.
ENAR - MongoDB on Heroku
package com.example;
import java.io.IOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoURI;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletOutputStream out = resp.getOutputStream();
DB db = openConnection();
// write
DBCollection coll = db.getCollection("test");
coll.insert(new BasicDBObject().append("changenum", "third"));
// read all
DBCursor cursor = coll.find();
out.write(("This is my " + cursor.next().get("changenum") + " change").getBytes());
out.flush();
out.close();
}
private DB openConnection() throws UnknownHostException {
MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
DB db = mongoURI.connectDB();
db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());
return db;
}
}
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.9.1</version>
</dependency>
@louismrose
Copy link
Author

Don't forget to add a MongoDB add-on to your Heroku app! I used the Mongo HQ add-on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment