Mongo Database Test

MongoDB usage is nice, I can store documents in any form I like for each Collection.  To get started, I need to setup a basic maven quickstart project using my favorite IDE, add the following dependencies to my pom.xml.




Do a maven clean and install (mvn clean install).  The dependencies will be downloaded.  Next, create a package under src/test/java named mongodb, then create a test class named with the following code:

package principles;

import com.mongodb.*;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

 * MongoMapTest
 * @author david.king
public class MongoMapTest {
 final String MONGO_DATABASE = "mongotest";
 final String MONGO_PRODUCTS_COLLECTION = "products";
 final String MONGO_HOST = "localhost";
 final int MONGO_PORT = 27017;

MongoClient mongoClient;
 DB database;
 DBCollection collection;

 public void testSerializeMapToMongoDb() {
 Map<String, Object> productMap = new HashMap<>();
 productMap.put("Product", "MongoTest");
 productMap.put("LifecycleMethods", Arrays.asList(new String[]{"Create", "Delete", "Update", "Read", "Archive"}));

System.out.printf("productMap MAP -> %s%n", productMap);

// insert into mongodb
 BasicDBObject document = new BasicDBObject();
 document.put("createdDate", new DateTime().toDate());

// find MongoTest product
 BasicDBObject ssQuery = new BasicDBObject();
 ssQuery.put("Product", "MongoTest");
 DBCursor results = collection.find(ssQuery);

while (results.hasNext()) {

 public void setUp() {
 try {
 mongoClient = new MongoClient(MONGO_HOST, MONGO_PORT);
 } catch (UnknownHostException e) {
 System.out.printf("%s%n", e.toString());

database = mongoClient.getDB(MONGO_DATABASE);
 collection = database.getCollection(MONGO_PRODUCTS_COLLECTION);

 public void tearDown() {
 collection = null;
 database = null;
 mongoClient = null;

Run the unit test and get the following output to the console (note, the _id will be unique):

productMap MAP -> {Product=MongoTest, LifecycleMethods=[Create, Delete, Update, Read, Archive]}
{ “_id” : { “$oid” : “529c98d8e4bc21644221f0ae”} , “Product” : “MongoTest” , “LifecycleMethods” : [ “Create” , “Delete” , “Update” , “Read” , “Archive”] , “createdDate” : { “$date” : “2013-12-02T14:27:36.556Z”}}


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s