Created
January 25, 2011 21:52
-
-
Save banker/795748 to your computer and use it in GitHub Desktop.
A sample program for MongoDB written in Java using the official Java driver.
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
import com.mongodb.Mongo; | |
import com.mongodb.DB; | |
import com.mongodb.DBCollection; | |
import com.mongodb.BasicDBObject; | |
import com.mongodb.DBObject; | |
import com.mongodb.DBCursor; | |
import com.mongodb.WriteConcern; | |
public class Test { | |
public static void main(String[] args) { | |
Mongo m; | |
try { | |
m = new Mongo("localhost", 27017); | |
WriteConcern w = new WriteConcern( 1, 2000 ); | |
m.setWriteConcern( w ); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
DB db = m.getDB( "training" ); | |
DBCollection coll = db.getCollection( "messages" ); | |
for(int i=0; i<10; i++) { | |
DBObject obj = new BasicDBObject(); | |
obj.put( "text", "Hello World!" ); | |
obj.put( "n", i ); | |
coll.insert(obj); | |
} | |
// Now iterate over the results | |
for( DBObject o : coll.find() ) { | |
System.out.println( o ); | |
} | |
System.out.println( "Count " + coll.count() ); | |
// Now delete the documents | |
System.out.println("Removing messages...\n"); | |
coll.remove( new BasicDBObject() ); | |
DBObject cmd = new BasicDBObject(); | |
cmd.put( "count", "messages" ); | |
System.out.println( "Count " + db.command( cmd ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment