C_J 发表于 2013-1-30 01:55:07

MongoDB on DAO with Java Language

A Quick Tour

Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath. The following code snippets come from the examples/QuickTour.java example code found in the driver.
Making A Connection

To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to. The database doesn't have to exist - if it doesn't, MongoDB will create it for you.
Additionally, you can specify the server address and port when connecting. The following example shows three ways to connect to the database mydb on the local machine :
import com.mongodb.Mongo;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.BasicDBObject;import com.mongodb.DBObject;import com.mongodb.DBCursor;Mongo m = new Mongo();Mongo m = new Mongo( "localhost" );Mongo m = new Mongo( "localhost" , 27017 );DB db = m.getDB( "mydb" ); 
At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations. 
Getting A List Of Collections

Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
Set<String> colls = db.getCollectionNames();for (String s : colls) {    System.out.println(s);} 
and assuming that there are two collections, name and address, in the database, you would see
nameaddressas the output.
Inserting a Document

Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as
<div class="code panel" style="border-top-width: 1px; border-left-width: 1px; border-bottom-width: 1px; border-right-width: 1px;"><div class="codeContent panelContent">{   "name" : "MongoDB",   "type" : "database",   "count" : 1,   "info" : {               x : 203,               y : 102             }}
页: [1]
查看完整版本: MongoDB on DAO with Java Language