Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The MongoDB component makes it easy to use MongoDB from OSGi. The component is a Managed Service Factory that enables you to configure MongoDB using Configuration Admin. This is a very light weight component and does not add APIs. The MongoDB Java Driver is already an OSGi bundle.

Usage

Deploy the `org.amdatu.mongo` bundle with your application and inject the MongoDBService into components as desired. The MongoDBService allows you to obtain a concrete DB instance for the configured MongoDB server.

Dependencies

The Amdatu MongoDB bundle depends on the following bundles:

  1. Apache Felix DependencyManager v3.1.0;
  2. An OSGi ConfigurationAdmin service implementation, for example Apache Felix ConfigAdmin v1.8.0;
  3. MongoDB Java Driver 2.11.13;
  4. (Optionally) an OSGi LogService implementation, for example Apache Felix LogService v1.0.1.

Configuration

The MongoDB service is configured by providing a factory configuration using the PID `org.amdatu.mongo`. This allows you to connect to different MongoDB instances.
Provisioning an empty configuration will result in a connection to a locally running MongoDB server (localhost:27017) using a database named `test`. All properties supported by the Mongo class are supported.

Example

MongoDB can easily be accessed through the injected MongoDBService API. The following example shows how to access the configured server and database, retrieve a collection and store an object:

Code Block
languagejava
titleMongoDB Example
DBCollection collection = m_mongoDBService.getDB().getCollection("demo");
collection.save(new BasicDBObject("mykey", "myvalue"));

 

Using Object Mapping

The Mongo Java API is very low level. It works with untyped properties instead of objects. This unleashes all the advanced features of MongoDB, but can be painful when simply storing and retrieving Java objects.
In these cases you can use an Object Mapping framework. There are several described on the MongoDB website. There is one framework in particular that we prefer: Jackson Mongo mapper. This project maps objects to BSON using the Jackson JSON serialization framework. If you are also using RESTful web services you can re-use the same mappings in your RESTful web services and Mongo code.

 

The following example shows how to retrieve and wrap a collection to map the contained BasicDBObjects to Objects, and save an Object without the use of a DBObject. 

Code Block
languagejava
titleMongoDB Object Mapping Example
DBCollection collection = m_mongoDBService.getDB().getCollection("demo");
JacksonDBCollection<MyClass, String> results = JacksonDBCollection.wrap(collection, MyClass.class, String.class);


MyClass myClassInstance = new MyClass();
results.save(myClassInstance);

 

License

The Amdatu MongoDB project is licensed under Apache License 2.0.