Databases Reference
In-Depth Information
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
class ChemSearch {
public static void main(String[] args) {
Mongo connection = new Mongo();
DB db = connection.getDB("search");
DBCollection chemicals = db.getCollection("chemicals");
/* ... */
}
}
This will connect to localhost:27017 and get the search.chemicals namespace.
Documents in Java must be instances of org.bson.DBObject , an interface that is basically
an ordered java.util.Map . While there are a few ways to create a document in Java, the
simplest one is to use the com.mongodb.BasicDBObject class. Thus, creating the docu-
ment that could be represented by the shell as {"x" : 1, "y" : "foo"} would look like
this:
BasicDBObject doc = new BasicDBObject();
doc.put("x", 1);
doc.put("y", "foo");
If we wanted to add an embedded document, such as "z" : {"hello" : "world"} , we
would create another BasicDBObject and then put it in the top-level one:
BasicDBObject z = new BasicDBObject();
z.put("hello", "world");
doc.put("z", z);
Then we would have the document {"x" : 1, "y" : "foo", "z" : {"hello" :
"world"}} .
From there, all of the other methods implemented by the Java driver are similar to the
shell. For instance, we could say chemicals.insert(doc) or chemicals.find(doc) . There
is full API documentation for the Java driver at http://api.mongodb.org/java and some
articles on specific areas of interest (concurrency, data types, etc.) at the MongoDB Java
Language Center .
Schema Design
The interesting thing about this problem is that there are thousands of possible prop-
erties for each chemical, and we want to be able to search for any of them efficiently.
Take two simple examples: silicon and silicon nitride. A document representing silicon
might look something like this:
{
"name" : "silicon",
 
Search WWH ::




Custom Search