Created
December 23, 2013 15:49
-
-
Save ludo1026/8099329 to your computer and use it in GitHub Desktop.
mongodb - test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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