JAVA操作MongoDB


1、驱动下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/


2、MongoDB API Docs for java

    http://api.mongodb.org/java/index.html

3、Getting started with Java

Introduction

This page is a brief overview of working with the MongoDB Java Driver.

For more information about the Java API, please refer to the onlineAPI Documentation for Java Driver.

A Quick Tour

Using the Java driver is very simple. First, be sure to include thedriver jar mongo.jar in your classpath. The following codesnippets come from the examples/QuickTour.java example codefound in the driver.

Making a Connection

To make a connection to a MongoDB, you need to have at the minimum, thename 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 whenconnecting. The following example shows three ways to connect to thedatabase mydb on the local machine :

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;

import java.util.Arrays;

// To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
// if it's a member of a replica set:
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                      new ServerAddress("localhost", 27018),
                                      new ServerAddress("localhost", 27019)));

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

At this point, the db object will be a connection to a MongoDB serverfor the specified database. With it, you can do further operations.

Note

The MongoClient instance actually represents a pool ofconnections to the database; you will only need one instance ofclass MongoClient even with multiple threads. See theconcurrency doc page for moreinformation.

The MongoClient class is designed to be thread safe and sharedamong threads. Typically you create only 1 instance for a givendatabase cluster and use it across your application. If for some reasonyou decide to create many MongoClient instances, note that:

  • all resource usage limits (max connections, etc) apply perMongoClient instance
  • to dispose of an instance, make sure you call MongoClient.close() toclean up resources

New in version 2.10.0: The MongoClient class is new in version 2.10.0. For releasesprior to that, please use the Mongo class instead.

Authentication (Optional)

MongoDB can be run in a secure mode where access to databases iscontrolled through name and password authentication. When run in thismode, any client application must provide a name and password beforedoing any operations. In the Java driver, you simply do the followingwith a MongoClient instance:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);

If the name and password are valid for the database, auth will betrue. Otherwise, it will be false. You should look at theMongoDB log for further information if available.

Most users run MongoDB without authentication in a trusted environment.

Getting a List Of Collections

Each database has zero or more collections. You can retrieve a list ofthem 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

name
address

as the output.

Getting a Collection

To get a collection to use, just specify the name of the collection tothe getCollection(String collectionName) method:

DBCollection coll = db.getCollection("testCollection");

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

Setting Write Concern

As of version 2.10.0, the default write concern isWriteConcern.ACKNOWLEDGED, but it can be easily changed:

mongoClient.setWriteConcern(WriteConcern.JOURNALED);

There are many options for write concern. Additionally, the defaultwrite concern can be overridden on the database, collection, andindividual update operations. Please consult the API Documentation fordetails.

Changed in version 2.10.0: Prior to version 2.10.0, the default write concern isWriteConcern.NORMAL. Under normal circumstances, clients willtypically change this to ensure they are notified of problemswriting to the database.

Inserting a Document

Once you have the collection object, you can insert documents into thecollection. For example, lets make a little document that in JSON wouldbe represented as

{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}

Notice that the above has an “inner” document embedded within it. To dothis, we can use the BasicDBObject class to create the document(including the inner document), and then just simply insert it into thecollection using the insert() method.

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));

coll.insert(doc);

Finding the First Document in a Collection Using findOne()

To show that the document we inserted in the previous step is there, wecan do a simple findOne() operation to get the first document in thecollection. This method returns a single document (rather than theDBCursor that the find() operation returns), and it’s useful for thingswhere there only is one document, or you are only interested in thefirst. You don’t have to deal with the cursor.

DBObject myDoc = coll.findOne();
System.out.println(myDoc);

and you should see

{ "_id" : "49902cde5162504500b45c2c" ,
  "name" : "MongoDB" ,
  "type" : "database" ,
  "count" : 1 ,
  "info" : { "x" : 203 , "y" : 102}}

Note

The _id element has been added automatically by MongoDB to yourdocument. Remember, MongoDB reserves element names that start with“_”/”$” for internal use.

Adding Multiple Documents

In order to do more interesting things with queries, let’s add multiplesimple documents to the collection. These documents will just be

{
   "i" : value
}

and we can do this fairly efficiently in a loop

for (int i=0; i < 100; i++) {
    coll.insert(new BasicDBObject("i", i));
}

Notice that we can insert documents of different “shapes” into the samecollection. This aspect is what we mean when we say that MongoDB is“schema-free”

Counting Documents in A Collection

Now that we’ve inserted 101 documents (the 100 we did in the loop, plusthe first one), we can check to see if we have them all using thegetCount() method.

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

and it should print 101.

Using a Cursor to Get All the Documents

In order to get all the documents in the collection, we will use thefind() method. The find() method returns a DBCursor object which allowsus to iterate over the set of documents that matched our query. So toquery all of the documents and print them out :

DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

and that should print all 101 documents in the collection.

Getting A Single Document with A Query

We can create a query to pass to the find() method to get a subset ofthe documents in our collection. For example, if we wanted to find thedocument for which the value of the “i” field is 71, we would do thefollowing ;

BasicDBObject query = new BasicDBObject("i", 71);

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

and it should just print just one document

{ "_id" : "49903677516250c1008d624e" , "i" : 71 }

You may commonly see examples and documentation in MongoDB which use $Operators, such as this:

db.things.find({j: {$ne: 3}, k: {$gt: 10} });

These are represented as regular String keys in the Java driver,using embedded DBObjects:

BasicDBObject query = new BasicDBObject("j", new BasicDBObject("$ne", 3)).
                                      append("k", new BasicDBObject("$gt", 10));

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection.For example, if we wanted to get all documents where "i" > 50, we could write :

query = new BasicDBObject("i", new BasicDBObject("$gt", 50));  // e.g. find all where i > 50

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

which should print the documents where i > 50.

We could also get a range, say 20 < i <= 30:

query = new BasicDBObject("i", new BasicDBObject("$gt", 20).
                                               append("$lte", 30));  // i.e.   20 < i <= 30
cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

Quick Tour of the Administrative Functions

Creating An Index

MongoDB supports indexes, and they are very easy to add on acollection. To create an index, you just specify the field that shouldbe indexed, and specify if you want the index to be ascending (1)or descending (-1). The following creates an ascending index on thei field :

coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

Getting a List of Indexes on a Collection

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} }

Getting A List of Databases

You can get a list of the available databases:

MongoClient mongoClient = new MongoClient();

for (String s : mongoClient.getDatabaseNames()) {
   System.out.println(s);
}

Dropping A Database

You can drop a database by name using a MongoClient instance:

MongoClient mongoClient = new MongoClient();
mongoClient.dropDatabase("myDatabase");

4、Release Notes

    https://github.com/mongodb/mongo-java-driver/wiki/Release-Notes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值