標籤:
本博文介紹了MongoDB,並詳細指引讀者在Ubuntu下MongoDB的安裝和使用。本教程在Ubuntu14.04下測試通過。
一、MongoDB介紹
MongoDB 是一個是一個基於分布式檔案儲存體的資料庫,介於關聯式資料庫和非關聯式資料庫之間,是非關聯式資料庫當中功能最豐富,最像關聯式資料庫的。他支援的資料結構非常鬆散,是類似json的bson格式,因此可以儲存比較複雜的資料類型。Mongo最大的特點是他支援的查詢語言非常強大,其文法有點類似於物件導向的查詢語言,幾乎可以實作類別似關聯式資料庫單表查詢的絕大部分功能,而且還支援對資料建立索引。
二、安裝MongoDB
MongoDB安裝很簡單,無需下載源檔案,可以直接用apt-get命令進行安裝。
開啟終端,輸入以下命令:
sudo apt-get install mongodb
如下:
安裝完成後,在終端輸入以下命令查看MongoDB版本:
mongo -version
輸出版本資訊,表明安裝成功,如下:
啟動和關閉mongodb命令如下:
service mongodb startservice mongodb stop
如下:
預設設定MongoDB是隨Ubuntu啟動自動啟動的。
輸入以下命令查看是否啟動成功:
pgrep mongo -l #注意:-l是英文字母l,不是阿拉伯數字1
如下:
三、使用MongoDBshell命令模式
輸入mongo進入shell命令模式,預設串連的資料庫是test資料庫,在此之前一定要確保你已經啟動了MongoDB,否則會出現錯誤,啟動之後運行成功,如下:
常用操作命令:
資料庫相關
show dbs:顯示資料庫列表
show collections:顯示當前資料庫中的集合(類似關聯式資料庫中的表table)
show users:顯示所有使用者
use yourDB:切換當前資料庫至yourDB
db.help() :顯示資料庫操作命令
db.yourCollection.help() :顯示集合操作命令,yourCollection是集合名
MongoDB沒有建立資料庫的命令,如果你想建立一個“School”的資料庫,先運行use School命令,之後做一些操作(如:建立聚集集合db.createCollection(‘teacher‘)),這樣就可以建立一個名叫“School”的資料庫。如下:
下面以一個School資料庫為例,在School資料庫中建立兩個集合teacher和student,並對student集合中的資料進行增刪改查基本操作(集合Collection相當於關係型資料庫中的表table)。
1、切換到School資料庫
use School #切換到School資料庫。MongoDB 無需預建立School資料庫,在使用時會自動建立
2、建立Collection
db.createCollection(‘teacher‘) #建立一個聚集集合。MongoDB 其實在插入資料的時候,也會自動建立對應的集合,無需預定義集合
如下:
3、插入資料
與資料庫建立類似,插入資料時也會自動建立集合。
插入資料有兩種方式:insert和save。
db.student.insert({_id:1, sname: ‘zhangsan‘, sage: 20}) #_id可選db.student.save({_id:1, sname: ‘zhangsan‘, sage: 22}) #_id可選
這兩種方式,其插入的資料中_id欄位均可不寫,會自動產生一個唯一的_id來標識本條資料。而insert和save不同之處在於:在手動插入_id欄位時,如果_id已經存在,insert不做操作,save做更新操作;如果不加_id欄位,兩者作用相同都是插入資料。如下:
添加的資料其結構是鬆散的,只要是bson格式均可,列屬性均不固定,根據添加的資料為準。先定義資料再插入,就可以一次性插入多條資料,如下:
運行完以上例子,student 已自動建立,這也說明 MongoDB 不需要預先定義 collection ,在第一次插入資料後,collection 會自動的建立。如下:
3、尋找資料
db.youCollection.find(criteria, filterDisplay)
criteria :查詢條件,可選
filterDisplay:篩選顯示部分資料,如顯示指定列資料,可選(當選擇時,第一個參數不可省略,若查詢條件為空白,可用{}做預留位置,如下例第三句)
db.student.find() #查詢所有記錄。相當於:select * from studentdb.student.find({sname: ‘lisi‘}) #查詢sname=‘lisi‘的記錄。相當於: select * from student where sname=‘lisi‘db.student.find({},{sname:1, sage:1}) #查詢指定列sname、sage資料。相當於:select sname,sage from student。sname:1表示返回sname列,預設_id欄位也是返回的,可以添加_id:0(意為不返回_id)寫成{sname: 1, sage: 1,_id:0},就不會返回預設的_id欄位了db.student.find({sname: ‘zhangsan‘, sage: 22}) #and 與條件查詢。相當於:select * from student where sname = ‘zhangsan‘ and sage = 22db.student.find({$or: [{sage: 22}, {sage: 25}]}) #or 條件查詢。相當於:select * from student where sage = 22 or sage = 25
查詢操作類似,這裡只給出db.student.find({sname: ‘lisi‘})查詢的,如下:
4、修改資料
db.youCollection.update(criteria, objNew, upsert, multi )
criteria: update的查詢條件,類似sql update查詢內where後面的
objNew : update的對象和一些更新的操作符(如$set)等,也可以理解為sql update查詢內set後面的。
upsert : 如果不存在update的記錄,是否插入objNew,true為插入,預設是false,不插入。
multi: mongodb預設是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。預設false,只修改匹配到的第一條資料。
其中criteria和objNew是必選參數,upsert和multi選擇性參數
舉例如下:
db.student.update({sname: ‘lisi‘}, {$set: {sage: 30}}, false, true) #相當於:update student set sage =30 where sname = ‘lisi‘;
操作如下:
5、刪除資料
db.student.remove({sname: ‘chenliu‘}) #相當於:delete from student where sname=‘chenliu‘
操作如下:
6、退出shell命令模式
輸入exit或者Ctrl+C退出shell命令模式
注意:MongoDB相較安全性更偏向易用性,預設是沒有開啟使用者權限的,如果想開啟使用者權限,可以參考Ubuntu下開啟MongoDB使用者權限。
Java API編程執行個體
第一步:下載Java MongoDB Driver驅動jar包,Java MongoDB Driver,預設的下載目錄為~/下載或者~/Downloads
第二步:開啟Eclipse,建立Java Project,建立Class,引入剛剛下載的jar包
第三步:編碼實現
下面是原始碼:
import java.util.ArrayList;import java.util.List;import org.bson.Document;import com.mongodb.MongoClient;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.model.Filters;public class TestMongoDB { /** * @param args */ public static void main(String[] args) { insert();//插入資料。執行插入時,可將其他三句函數調用語句注釋掉,下同// find(); //尋找資料// update();//更新資料// delete();//刪除資料 } /** * 返回指定資料庫中的指定集合 * @param dbname 資料庫名 * @param collectionname 集合名 * @return */ //MongoDB無需預定義資料庫和集合,在使用的時候會自動建立 public static MongoCollection<Document> getCollection(String dbname,String collectionname){ //執行個體化一個mongo用戶端,伺服器位址:localhost(本地),連接埠號碼:27017 MongoClient mongoClient=new MongoClient("localhost",27017); //執行個體化一個mongo資料庫 MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname); //擷取資料庫中某個集合 MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname); return collection; } /** * 插入資料 */ public static void insert(){ try{ //串連MongoDB,指定串連資料庫名,指定串連表名。 MongoCollection<Document> collection= getCollection("test","student"); //執行個體化一個文檔,文檔內容為{sname:‘Mary‘,sage:25},如果還有其他欄位,可以繼續追加append Document doc1=new Document("sname","Mary").append("sage", 25); //執行個體化一個文檔,文檔內容為{sname:‘Bob‘,sage:20} Document doc2=new Document("sname","Bob").append("sage", 20); List<Document> documents = new ArrayList<Document>(); //將doc1、doc2加入到documents列表中 documents.add(doc1); documents.add(doc2); //將documents插入集合 collection.insertMany(documents); System.out.println("插入成功"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } /** * 查詢資料 */ public static void find(){ try{ MongoCollection<Document> collection = getCollection("test","student"); //通過遊標遍曆檢索出的文檔集合 // MongoCursor<Document> cursor= collection.find(new Document("sname","Mary")). projection(new Document("sname",1).append("sage",1).append("_id", 0)).iterator(); //find查詢條件:sname=‘Mary‘。projection篩選:顯示sname和sage,不顯示_id(_id預設會顯示) //查詢所有資料 MongoCursor<Document> cursor= collection.find().iterator(); while(cursor.hasNext()){ System.out.println(cursor.next().toJson()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } /** * 更新資料 */ public static void update(){ try{ MongoCollection<Document> collection = getCollection("test","student"); //更新文檔 將文檔中sname=‘Mary‘的文檔修改為sage=22 collection.updateMany(Filters.eq("sname", "Mary"), new Document("$set",new Document("sage",22))); System.out.println("更新成功!"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } /** * 刪除資料 */ public static void delete(){ try{ MongoCollection<Document> collection = getCollection("test","student"); //刪除合格第一個文檔 collection.deleteOne(Filters.eq("sname", "Bob")); //刪除所有合格文檔 //collection.deleteMany (Filters.eq("sname", "Bob")); System.out.println("刪除成功!"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }}
每次執行完程式,都可以返回shell模式查看結果。如:在eclipse執行完更新操作後,在shell模式輸入db.student.find(),可以查看student集合的所有資料,如下:
Ubuntu下MongoDB的安裝和使用