MongoDB Java Driver notes

A few notes on using the MongoDB Java Driver API:

Getting a connection:

MongoClient client = new MongoClient("localhost", 27017);
DB db = client.getDB("test");

Get a collection from connected db:

DBCollection collection = db.getCollection("example");

 

Find all docs in collection and iterate through results:

DBCursor c = collection.find();
try {
   while(c.hasNext()) {
       System.out.println(c.next());
   }
} finally {
   c.close();
}

 

Simple findOne query, matching a doc with properyname = value:

DBObject result = collection.findOne(new BasicDBObject("propertyname", "value"));

 

Find all, sort on property ‘example’ ascending (1=asc, -1=desc), and limit to 10 results:

DBCursor c = collection.find()
    .sort(new BasicDBObject("example", 1))
    .limit(10);

 

Serialize results of a cursor to JSON (tip from here):

JSON json = new JSON();
String jsonString = json.serialize(c);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.