MongoDb學習

下週起,有個小項目中要使用MogoDb來進行存儲,選用它,考慮到其面向對象存儲,且業界表現不俗的口碑。另外一個爲了以後更大的項目能應用,也算一點技術積累吧。

週末無事,在官網文檔的幫忙下,邊看邊寫了一些測試用例,簡單使用後,算是懂得如何使用了。

官網上相關資料進行了簡單的記錄,對入門算是有個簡單的幫忙:

一.下載與安裝
下載地址:http://www.mongodb.org/downloads
win下:
解壓bin目錄下所有exe文件到一個目錄,比如c:\mongodb
在此目錄下新建data目錄,
這樣在命令行執行
mongod.exe --dbpath c:\mongdb\data 
即可啓動mongodb了,數據保存在上面指定的data目錄下
mongodb 不同語言驅動下載地址:

二.基本使用
2.1 MongoClient說明
1.MongoClient 線程安全
2.如果多個MongoClient實例,需要注意:配製每個實例的usage limits(max connections) , 另外需要釋放實例時,需要MongoClient.close.
3.可以認證:
MongoClient提供了認證的功能:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);
大部分情況不用auth.

2.2 獲取集合列表:
getting a list of collections
Set<String> colls = db.getCollectionNames();

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

獲取collection
getCollection(String collectionName);
DBCollection coll = db.getCollection("testCollection");
Once you have this collection object, you can now do things like insert data, query for data, etc

2.3 設置mongodb寫(有很多種方式)
2.10.0之前默認爲
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
Write operations that use this write concern will return as soon as the message is written to the socket. Exceptions are raised for network issues, but not server errors.
This field has been superseded by WriteConcern.UNACKNOWLEDGED, and may be deprecated in a future release
2.10.0以後改寫爲
WriteConcern.ACKNOWLEDGED:
Write operations that use this write concern will wait for acknowledgement from the primary server before returning. Exceptions are raised for network issues, and server errors.

2.4 mongodb插入document
insert a document
a json object 如下:
a json
{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}
使用BaseDBObject
BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
注意:
insert 插入相同的元素時會報錯。
還對於save方法,則會更新此元素。

mongodb查找document
簡單使用findOne(),得到collection第一個document.
find() 方法返回DBCursor 可查找找有的document.
每個object 插入時會自動增加_id對象。 另外mongodb保留的元素命名是以"_"/"$".內部使用。

2.5 使用DBCursor獲取此collection的所有元素
DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

2.6 使用query方法查詢一個document
BasicDBObject query = new BasicDBObject("i", 71);
cursor = coll.find(query)
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

2.7 mongodb範圍查詢
經常看示例,DB查詢使用“$”操作符,此操作符爲範圍查詢,如下:
db.things.find({j: {$ne: 3}, k: {$gt: 10} });
內部是使用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();
}

使用query 獲取documents 集合。
使用collection查詢,如果想查詢"i" > 50 可以如下:
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();
}
如果是20 < i <= 30,
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).
                                               append("$lte", 30));  // i.e.   20 < i <= 30
三.Mongodb的管理功能
3.1 創建index
Mongodb支持索引,通過collection可以很容易增加,爲了創建索引,只需要說明這個field應該indexed.
而且索引可以升序或者降序。
如下升序創建如下:
coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

3.2 獲取一個列表上的索引集合
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
   System.out.println(o);
}

3.3 獲取database集合
MongoClient mongoClient = new MongoClient();
for (String s : m.getDatabaseNames()) {
   System.out.println(s);
}

3.4 丟棄一個databases
MongoClient mongoClient = new MongoClient();
mongoClient.dropDatabase("myDatabase");

四.java 類型
(http://docs.mongodb.org/ecosystem/drivers/java-types/#java-types)
4.1 object Ids
com.mongodb.ObjectId 可以被用來創建唯一的ids.
ObjectId id = new ObjectId();
id.getInc();

4.2 支持正則表達式
Pattern john = Pattern.compile("joh?n", CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", john);
// finds all people with "name" matching /joh?n/i
DBCursor cursor = collection.find(query);

4.3 dates/times
可以使用java.util.Date用做日期
Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);
collection.save(time);

4.4 database引用。
com.mongodb.DBRef 能夠用於保存數據庫引用
簡單瞭解後,使數據結構變得有些複雜了。(暫不發表觀點)

4.5 Binary數據
byte[]會自動會被wrap成Binary類型,另外Binary類表示Binary Object-自定義的二進制類型

4.6 Timestamp data
時間戳在mongodb中是一個特別的對象,基於時間作爲ID ,以pair表示(秒時間,自增長ID), 特別被用中同步的操作日誌。 一個時間戳使用BSONTimestamp 類表示。

4.7 Code data
code object被用來表示 javascipt code,例如當執行system.js中的函數時,Code與CodeWScope 類可以被用來表示這些數據。

4.8 數組
java中任何對象繼續List 將會被保存爲數組。
如下:
{
    "x" : [
           1,
           2,
           {"foo" : "bar"},
           4
    ]
}
可以編碼如下:
ArrayList x = new ArrayList();
x.add(1);
x.add(2);
x.add(new BasicDBObject("foo", "bar"));
x.add(4);
BasicDBObject doc = new BasicDBObject("x", x);

以上相關資料在官網都可以找到,如果OK的話,還是建議查看官網相關資料。


(mongodb 集羣搭建:http://www.lanceyan.com/tech/mongodb/mongodb_cluster_1.html)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章