Java Driver for MongoDB

1.   Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath.


2.   You can specify the server address and port when connecting:

Mongo m = new Mongo( "localhost" , 27017 );

DB db = m.getDB( "mydb" ); 

 

Or , you can pass in a MongoURI object which contains the standard connection string:

Mongo m = new Mongo(new URI(“mongodb://user1:password1@localhost:27017/mydb”));

 

 

Or, simply, you get the Mongo object from MongoURI :

Mongo m = new URI(“mongodb://user1:password1@localhost:27017/mydb”).connect();

 

 

Or, even simply, you get the DB object right from MongoURI :

DB db = new URI(“mongodb://user1:password1@localhost:27017/mydb”).connectDB();

 

 


3.   The Mongo class is designed to be thread safe and shared among threads. The Mongo object instance actually represents a pool of connections to the database; Typically you create only 1 instance for a given DB cluster and use it across your app. All resource usage limits (max connections, etc) apply per mongo instance. And to dispose of an instance, make sure you call mongo.close() to clean up resources


4.   MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations:

boolean auth = db.authenticate(myUserName, myPassword);
 

 

If the name and password are valid for the database, auth will be true .

 

5.  Y ou can retrieve a list of collections from the db :

Set<String> colls = db.getCollectionNames();

 

for (String s : colls) {

    System.out.println(s);

} 
 

To get a collection to use:

DBCollection coll = db.getCollection("testCollection")
 

 

Once you have this collection object, you can now do things like insert data, query for data, etc.

 

6.   To insert a document represented as :

{

   "name" : "MongoDB",

   "type" : "database",

   "count" : 1,

   "info" : {

               x : 203,

               y : 102

             }

} 
 

You can :

   

BasicDBObject doc = new BasicDBObject();

 

  doc.put("name", "MongoDB");

  doc.put("type", "database");

  doc.put("count", 1);

 

  BasicDBObject info = new BasicDBObject();

 

  info.put("x", 203);

  info.put("y", 102);

 

  doc.put("info", info);

 

  coll.insert(doc); 
 

 

Note: MongoDB reserves element names that start with "_ " and "$ " for internal use.

 

7.   findOne () retrieve the first document of the collection:

DBObject myDoc = coll.findOne();
 

 

 

8.   To check the number of documents contained in the collection:

System.out.println(coll.getCount());
 

 

 

9.   In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query:

DBCursor cur = coll.find();

while(cur.hasNext()) {

            System.out.println(cur.next());

} 

10.  To find the document for which the value of the "j " field is not equal to 3 and value of the “k ” field is greater than 10 :

   

BasicDBObject query = new BasicDBObject();

        query.put("j", new BasicDBObject("$ne", 3));

        query.put("k", new BasicDBObject("$gt", 10));

DBCursor cur = coll.find(query);

        while(cur.hasNext()) {

            System.out.println(cur.next());

        } 
 

 

 

11.   To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1 ) or descending (-1 ):

coll.createIndex(new BasicDBObject("i", 1));

 

12.   You can get a list of the indexes on a collection :

List<DBObject> list = coll.getIndexInfo();

         for (DBObject o : list) {

            System.out.println(o);

        } 
 

and you should see something like:

{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} } 
 

 

 

13.   You can get a list of the available databases:

Mongo m = new Mongo();

         for (String s : m.getDatabaseNames()) {

            System.out.println(s);

        } 
 

 

14.   You can drop a database by :

m.dropDatabase("my_new_db");
 

 

 

15.   For details of Java API for MongoDB , please refer:

http://api.mongodb.org/java/current/

猜你喜欢

转载自seanzhou.iteye.com/blog/1573567