MongoDB Guice Bindings

This package provides simple bindings to MongoDB, using giulius for loading the host and port and setting up Guice bindings. This project does not attempt to do any kind of ORM stuff, but just makes working with MongoDB + Guice simple.

The entry-point is the Guice module MongoModule. You can pass a database name to its constructor, or it will try to extract the application's main-class name if the default constructor is used.

Individual collections can be bound so they can be injected using @Named("someName") DBCollection - you need to tell the MongoModule what the mapping between collection names and names used in code is. I.e. if you want to have a collection named "ttusers" injected when a class references @Named ("users") DbCollection users then you would do:

new MongoModule("myDb").bindCollection("users", "ttusers")
        
If no String database name is provided, MongoModule will attempt to figure out the main class name from the current call stack (if you wind up with weird database names like "execute", this is why).

Creating Indexes and Configuring Collections

Sometimes it is desirable to configure some aspects of collections at the time they are created. For this purpose, you can subclass MongoInitializer - and have more than one of these if necessary. This class has hook methods which are called before and after collections and databases are created, allowing you to customize the creation options for a collection (for example, to create a capped collection), or to create indexes on a collection immediately after it is created.

To use it, all you need to do is to bind them as eager singletons; MongoModule has an add(Class<? extends MongoInitializer>) method to facilitate that.

Here is an example which sets an index on one collection, and ensures that another is created as a capped collection:

    static class Ini extends MongoInitializer {

        @Inject
        public Ini(MongoInitializer.Registry registry) {
            super(registry);
        }

        @Override
        protected void onCreateCollection(DBCollection collection) {
            switch (collection.getName()) {
                case "users":
                    collection.ensureIndex(new BasicDBObject("name", "hashed"));
            }
        }

        @Override
        protected void onBeforeCreateCollection(String name, BasicDBObject params) {
            switch (name) {
                case "cappedStuff":
                    System.out.println("Set up capped");
                    params.append("capped", true).append("size", 10000).append("max", 1000);
            }
        }
    }