Skip to content

Instantly share code, notes, and snippets.

@daniel-roberts-10gen
Created June 29, 2012 11:28
Show Gist options
  • Save daniel-roberts-10gen/3017465 to your computer and use it in GitHub Desktop.
Save daniel-roberts-10gen/3017465 to your computer and use it in GitHub Desktop.
MongoDB Scratch pad
/**
* Example code for MongoDB CRUD
* and commands.
*
*/
package com.tengen.demo;
import com.mongodb.*;
import com.mongodb.util.*;
import com.mongodb.gridfs.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
/**
* @author danielroberts at 10gen
*
*/
public class Main {
/*
* Create connection to MongoDB
*/
private Mongo m = null;
/*
* static variables
*/
private static int NUM_NODES = 2; //Number of nodes that should be written to.
private static int W_TIMEOUT = 5000; //Number of milliseconds for timeout exception.
/*
* Constructor
*/
public Main() throws Exception
{
List<ServerAddress> address = new ArrayList<ServerAddress>();
address.add( new ServerAddress( "127.0.0.1" , 27017 ) );
//address.add( new ServerAddress( "127.0.0.1" , 27018 ) );
//address.add( new ServerAddress( "127.0.0.1" , 27019 ) );
//address.add( new ServerAddress( "127.0.0.1" , 20000 ) );
m = new Mongo(address);
m.setReadPreference(ReadPreference.SECONDARY);
}
/*
* Insert data in to MongoDB
* User the Mongo object to get hold of the database and collection
* to write to.
*/
public void insert() throws Exception
{
//Starting insert
System.out.println("Start insert();");
//Get database.
DB db = m.getDB("test");
//Get the collection
DBCollection col = db.getCollection("stuff");
//How many documents are their in the collection.
System.out.println("Collection count():"+col.getCount());
//Create a WriteConcern to ensure that data it written to more that 1 node before returning.
//WriteConcern wc = new WriteConcern(NUM_NODES,W_TIMEOUT);
//WriteConcern wc = new WriteConcern();
WriteConcern wc = WriteConcern.NONE;
//Insert data in to the collection.
col.insert(createDocument("Daniel","Roberts","Oracle","200 Aldersgate, London"),wc);
col.insert(createDocument("Chris","Harris","10gen","200 Aldersgate, London"),wc);
col.insert(createDocument("Gerry","Treacy","10gen","123 Guiness Street, Dublin"),wc);
col.insert(createDocument("Alvin","Richards","10gen","555 University, Palo Alto"),wc);
}
//Create BasicDBObject to insert into MongoDB.
private BasicDBObject createDocument(String fn, String ln, String company, String address)
{
BasicDBObject dbo = new BasicDBObject();
dbo.put("fn",fn);
dbo.put("ln",ln);
dbo.put("company",company);
dbo.put("address",address);
return dbo;
}
public void insertUUID() throws Exception
{
DB db = m.getDB("test");
//Get the collection
DBCollection col = db.getCollection("uuuu");
BasicDBObject dbo = new BasicDBObject();
dbo.put("uuid", UUID.randomUUID());
col.insert(dbo);
}
/*
* Qurey data from MongoDB
*/
public void query() throws Exception
{
this.printAddresses();
//Get hold of the test database from the Mongo object.
DB db = m.getDB("test");
//Find all the all the collections in the test database.
//show dbs from mongo shell
Set<String> colls = db.getCollectionNames();
for (String s : colls)
{
System.out.println(s);
}
//Get a hold of the stuff collection in order to do some queries.
DBCollection col = db.getCollection("stuff");
//Queries are created using BasicDBObject
BasicDBObject q = new BasicDBObject();
//Create a query using a regular expression. This is using standard java.util.regex.*
q.put("fn", Pattern.compile("^D")); //Regex
//{fn: /^D/}
//Return the JSON query string.
System.out.println("Query Object:"+q.toString());
//Execute the query and get a DBCursor object back to iterate over.
//(DBObject)JSON.parse("{a:1,b:2}")
//DBCursor cur = col.find((DBObject)JSON.parse("{a:1,b:2}"));
DBCursor cur = col.find(q);
System.out.println("Cursor length,count:"+cur.length()+":"+cur.size());
Iterator<DBObject> i = cur.iterator();
while(i.hasNext())
{
System.out.println(i.next().toString());
}
}
/**
*
* */
public void queryTest() throws Exception {
DB db = m.getDB("mtest");
DBCollection col = db.getCollection("mbucket");
//Query {company:'tengen',user:'dmr'}
DBObject query = (DBObject)JSON.parse("{company:'tengen',user:'dmr'}");
//Projection {_id:0, conversation:1, msgs : {$slice:-1}}
DBObject projection = (DBObject)JSON.parse("{_id:0, conversation:1, msgs : {$slice:-1}}");
DBCursor cur = col.find(query, projection);
//Sort {'msgs.message.ts':1}
cur.sort((DBObject)JSON.parse("{'lastmessage':-1}"));
HashMap<String, String> lastMsgs = new HashMap<String, String>(5);
Iterator<DBObject> i = cur.iterator();
while(i.hasNext())
{
BasicDBObject dbo = (BasicDBObject)i.next();
BasicDBList dbl = (BasicDBList)dbo.get("msgs");
BasicDBObject msg = (BasicDBObject)dbl.get(0);
String conv = dbo.get("conversation").toString();
String l_msg = msg.get("message").toString();
if(!lastMsgs.containsKey(conv))
{
lastMsgs.put(conv, l_msg);
}
}
System.out.println(lastMsgs.toString());
cur.close();
}
/*
* Update data in MongoDB.
*/
public void update() throws Exception
{
//Get hold of the test database from the Mongo object.
DB db = m.getDB("test");
//Get hold of the collection from the database.
DBCollection col = db.getCollection("blah");
//Build the update query again with the BasicDBObject.
BasicDBObject query = new BasicDBObject();
query.put("fn", "Daniel");
//Use the $set modifier to update documents.
BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("address","400 Aldersgate"));
System.out.println(update.toString());
col.update(query, update,false,true);
CommandResult cr = db.getLastError();
System.out.println("getLastError"+cr.toString());
}
/*
* Run a command on the database.
* Examples: isMaster, dbstats, listCommands,connPoolStats, replSetGetStatus
*/
public void runCommand() throws Exception
{
System.out.println("runCommand()");
/*
* Get hold of the admin database, not all command require the admin database.
* See db.listCommands() from sell for more information.
*/
DB db = m.getDB("admin");
/*
* Commands are issued by building JSON through the BasicDBOBject, same as for CRUD.
* console -> db.runCommand({'replSetGetStatus',1}); = rs.status(); = same as following code..
*/
BasicDBObject dbCommand = new BasicDBObject("replSetGetStatus","1");
CommandResult cr = db.command(dbCommand);
System.out.println(cr.toString());
}
/**
* print addresses
*/
private void printAddresses()
{
List<ServerAddress> addrs = m.getAllAddress();
Iterator<ServerAddress> i = addrs.iterator();
while(i.hasNext())
{
System.out.println("Addr: "+i.next());
}
}
public void insertJSON() throws Exception
{
//Starting insert
System.out.println("Start insert(JSON);");
//Get database.
DB db = m.getDB("test");
//Get the collection
DBCollection col = db.getCollection("uuuu");
//How many documents are their in the collection.
col.save((DBObject)JSON.parse("{a:'d376cc14-af33-4f6d-978b-4ab4af6079e0',b:2}"));
}
public void insertGridFS() throws Exception
{
// /Users/danielroberts/Downloads/Daniel Roberts.jpg
String newFileName = "dmr";
File imageFile = new File("/Users/danielroberts/Downloads/Daniel Roberts.jpg");
DB db = m.getDB("test");
GridFS gfsPhoto = new GridFS(db,"photos");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setContentType("blah/jpg");
gfsFile.setFilename(newFileName);
gfsFile.setId("abc1234");
BasicDBObject meta = new BasicDBObject();
meta.put("fn","Daniel");
gfsFile.setMetaData(meta);
//save
gfsFile.save();
//End
System.out.println("insert GridFS finished.");
}
public void getGridFS() throws Exception
{
DB db = m.getDB("test");
String newFileName = "dmr";
GridFS gfsPhoto = new GridFS(db, "photos");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);
imageForOutput.writeTo("/Users/danielroberts/Downloads/"+newFileName);
}
public void insert(DBObject dbo) throws Exception
{
DB db = m.getDB("test");
//Get the collection
DBCollection col = db.getCollection("bar");
col.insert(dbo);
}
public DBObject build() throws Exception
{
DBObject dbo = BasicDBObjectBuilder.start()
.add("fn", "Daniel")
.add("ln", "Roberts")
.add("data",BasicDBObjectBuilder.start().add("a", 1)
.add("b",2).get())
.add("more","data").get();
System.out.println(dbo.toString());
return dbo;
}
public void fAndM() throws Exception
{
DB db = m.getDB("test");
//Get the collection
DBCollection col = db.getCollection("bar");
DBObject doc = col.findAndModify( new BasicDBObject(), //query
null, //fields
null, //sort
true, //boolean remove
null, //update obj
false, //return new
false); //Upsert */
System.out.println("fAndM:"+doc);
}
/**
*
* example queries and updates.
* db.stuff.update({"names.language":"en"}, {"$set" : { "names.$.state" : "London"}} );
* db.stuff.update({fn:'Daniel'},{$set : {age:21}}); //set adds key if it doesn't exist.
* db.stuff.find({age : {$lte:38}}); //$lt => <,$gt => >,$gte => =<, $ne => !=
* db.stuff.find({fn: /D/}); // regex
*/
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
Main main = new Main();
/*while(true)
{
try
{
main.insert();
}
catch(Exception e)
{
System.out.println("Exeception "+e.getMessage());
e.printStackTrace();
}
finally
{
Thread.sleep(2000);
}
}//*/
//main.fAndM();
main.insertGridFS();
//main.getGridFS();
//main.insertJSON();
//main.query();
//main.update();
//main.runCommand();
//main.insertUUID();
/*/UUID u1 = UUID.randomUUID();
System.out.println(u1.toString());
//System.out.println(UUID.fromString("Daniel"));
System.out.println(UUID.nameUUIDFromBytes("Daniel".getBytes()));//*/
//main.insert(main.build());
//main.queryTest();
//System.out.println("End.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment