Skip to content

Instantly share code, notes, and snippets.

@ludo1026
Created December 23, 2013 15:49
Show Gist options
  • Save ludo1026/8099329 to your computer and use it in GitHub Desktop.
Save ludo1026/8099329 to your computer and use it in GitHub Desktop.
mongodb - test
package org.tuto.mongodb;
import com.mongodb.*;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class MongoDBTest {
@Test
public void crud() throws Exception {
// Connection
MongoClient client = new MongoClient("localhost", 27017);
// Drop database
client.dropDatabase("test");
// Create database
DB db = client.getDB("test");
// Documents collection
DBCollection collection = db.getCollection("books");
// Insert documents in collection
List<DBObject> documents = new ArrayList<DBObject>();
documents.add(new BasicDBObject().append("title", "The Hunger Games"));
documents.add(new BasicDBObject().append("title", "The Help"));
documents.add(new BasicDBObject().append("title", "Harry Potter and the Sorcerer's Stone"));
documents.add(new BasicDBObject().append("title", "A Thousand Splendid Suns"));
documents.add(new BasicDBObject().append("title", "Harry Potter and the Deathly Hallows"));
collection.insert(documents);
// Get all documents from collection
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
cursor.close();
// Find one book by title
BasicDBObject query = new BasicDBObject("title", "The Help");
cursor = collection.find(query);
Assert.assertEquals(1, cursor.count());
DBObject document = cursor.next();
Assert.assertEquals("The Help", document.get("title"));
cursor.close();
// Drop database
client.dropDatabase("test");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment