This page is a brief overview of working with the MongoDB Java Driver.java
這是使用MongoDB java驅動的簡單說明。mongodb
For more information about the Java API, please refer to the online API Documentation for Java Driver 數據庫
想獲取更多關於java的API,請查看在線API文檔。安全
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.服務器
使用很簡單。首先將驅動mongo.jar放入classpath。下面的代碼段是驅動中例子examples/QuickTour.java中的內容app
建立鏈接ide
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.oop
建立鏈接至少須要你要鏈接的數據庫名。若是數據庫不存在,MongoDB會自動建立。ui
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 :this
此外,你還能夠指定數據庫服務器地址和端口。下邊的例子中有三種鏈接本機mydb數據庫方法:
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(); // or Mongo m = new Mongo( "localhost" ); // or 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.
db對象就是鏈接服務器中指定數據庫的鏈接。使用他你能夠作不少操做。
Note: The Mongo object instance actually represents a pool of connections to the database; you will only need one object of class Mongo even with multiple threads. See the concurrency doc page for more information.
注意:Mongo的實例是數據庫鏈接池;在多個線程中只須要一個實例。更多的介紹請參考concurrency文檔。
The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given DB cluster and use it across your app. If for some reason you decide to create many mongo intances, note that:
Mongo類是線程安全和共享的。能夠在整個應用中使用他。若是你想建立多個Mongo實例,注意:
all resource usage limits (max connections, etc) apply per mongo instance
每一個mongo實例的資源使用限制
to dispose of an instance, make sure you call mongo.close() to clean up resources
記得使用mongo.close()關閉資源
Authentication (Optional)
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. In the Java driver, you simply do the following with the connected mongo object :
MongoDB能夠運行在經過用戶名和密碼控制的安全的模式下。當以安全模式運行時,任何客戶端應用程序的操做必須驗證用戶名和密碼。在java中,驗證很簡單:
boolean auth = db.authenticate(myUserName, myPassword);
If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.
若是用戶名和密碼正確,auth值爲true。錯誤爲false。在日誌中能夠看到更多有效的信息。
Most users run MongoDB without authentication in a trusted environment.
不少用戶將MongoDB以非受權模式運行在安全的環境中。
查詢Collection的集合(Collection相似於表)
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
每一個數據庫能夠有任意個collection。經過db對象能夠檢索並打印出來:
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兩個collection,結果輸出入下
name address
as the output.
Getting A Collection
獲得Collection
To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
要使用collection,使用getCollection(String collectionName) 方法傳入collection的名稱:
DBCollection coll = db.getCollection("testCollection")
Once you have this collection object, you can now do things like insert data, query for data, etc
獲得collection對象後就能夠進行插入、查詢等操做了。
插入一個文檔(相似一條記錄)
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
獲得collection對象就能夠把documents插入到collection中。例如,建立一個以下的JSON文檔
{ "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { x : 203, y : 102 } }
Notice that the above has an "inner" document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.
注意,上面的文檔中有個內部文檔(就是{ x : 203, y : 102})。存儲上面的文檔,可使用BasicDBObject 類來建立文檔(包括inner文檔),使用insert()方法能夠簡單的把文檔插入collection中。
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);
使用findOne()方法查找collection中的第一個文檔document
To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.
可使用findOne()操做來查找collection中的第一個文檔來顯示上一步中插入的文檔。方法返回一個文檔,用來找只有一個文檔或第一條文檔很實用。能夠不使用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 your document. Remember, MongoDB reserves element names that start with "_"/"$" for internal use.
注意,_id元素是MongoDB自動添加的。MongoDB內部的元素以"_"/"$"開始。
添加多個文檔
In order to do more interesting things with queries, let's add multiple simple 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().append("i", i)); }
Notice that we can insert documents of different "shapes" into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free"
注意,能夠在一個collection中插入不一樣類型的文檔。就是說MongoDB是"schema-free"(什麼意思?)
統計collection中全部的document數量
Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the getCount() method.
如今,插入了101個文檔(循環的100個和第一個),使用getCount()檢查一下。
System.out.println(coll.getCount());
and it should print 101.
輸出結果是101.
使用遊標查找全部的文檔
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. So to query all of the documents and print them out :
使用find()來查找全部的document。find()方法查詢返回一個能夠遍歷文檔集合的DBCursor 對象。以下:
DBCursor cur = coll.find(); while(cur.hasNext()) { System.out.println(cur.next()); }
and that should print all 101 documents in the collection.
打印全部的document
Getting A Single Document with A Query
查詢出單個文檔
We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;
能夠經過find()方法查找部分document,例如,若是想查找i=71的document,這樣作
BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
and it should just print just one document
會打印找到的單個document
{ "_id" : "49903677516250c1008d624e" , "i" : 71 }
You may commonly see examples and documentation in MongoDB which use $ Operators, such as this:
MongoDB文檔和例子中常常出現$操做符,以下
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(); query.put("j", new BasicDBObject("$ne", 3)); query.put("k", new BasicDBObject("$gt", 10)); cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
查找多個文檔
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 :
例如,想找"i">50的文檔,這樣作:
query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // e.g. find all where i > 50 cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
which should print the documents where i > 50. We could also get a range, say 20 < i <= 30 :
會打印出i>50的文檔。也能夠查找範圍如20<i<=30:
query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
建立索引
MongoDB supports indexes, and they are very easy to add on a collection. 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). The following creates an ascending index on the "i" field :
MongoDB支持索引,而且很容易添加。只須要指定索引的字段和排序(升序1,降序-1)。下面是建立i降序索引的例子:
coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending
查詢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} }
管理方法
查詢全部數據庫
You can get a list of the available databases:
打印出可用的數據庫
Mongo m = new Mongo(); for (String s : m.getDatabaseNames()) { System.out.println(s); }
刪除數據庫
You can drop a database by name using the Mongo object:
經過名稱刪除
m.dropDatabase("my_new_db");
--------------------------------------------------------------------------------
Added by Rian Murphy, last edited by Scott Hernandez on May 05, 2011
保存自http://www.mongodb.org/display/DOCS/Java+Tutorial
翻譯:Noday(noday.net)於20110629晚 (沒過4級的傢伙,全憑感受翻譯,歡迎討論指正)