MongoDB安裝很簡單悯恍,無需下載源文件鞭达,可以直接用apt-get命令進行安裝话肖。?
打開終端,輸入以下命令:
sudoapt-get install mongodb
截圖如下:?
安裝完成后蜡峰,在終端輸入以下命令查看MongoDB版本:
mongo -version
輸出版本信息了袁,表明安裝成功,截圖如下:?
啟動和關(guān)閉mongodb命令如下:
service mongodb start
service mongodb stop
截圖如下:?
默認(rèn)設(shè)置MongoDB是隨Ubuntu啟動自動啟動的湿颅。?
輸入以下命令查看是否啟動成功:
pgrep mongo-l#注意:-l是英文字母l载绿,不是阿拉伯?dāng)?shù)字1
截圖如下:?
卸載MongoDB
sudoapt-get --purge remove mongodb mongodb-clients mongodb-server
二. 重啟系統(tǒng)以后mongo程序要自己重新手動啟動,步驟如下:
1.運行“locate mongo”命令查看系統(tǒng)默認(rèn)把mongo裝到了哪里油航,這里主要關(guān)注三個東西.
(1)一個是名為“mongod”的程序的位置(他相當(dāng)于mongo數(shù)據(jù)庫的Server崭庸,需要一直在后臺運行,我的路徑:/usr/bin/mongod);
(2)一個是mongo 數(shù)據(jù)庫log日志文件的位置(log日志文件要查看到具體的文件名,具體用法在后面有介紹,我的路徑:/var/log/mongodb/mongodb.log);
(3)一個是mongo的log日志的位置(我的路徑:/var/log/mongodb/mongodb.log)劝堪。
2.先進入mongod所在的目錄(/usr/bin/mongod)冀自,然后運行“./mongod --dbpath /var/lib/mongodb/ --logpath /var/log/mongodb/mongodb.log --logappend &”
--dbpath:指定mongo的數(shù)據(jù)庫文件在哪個文件夾
--logpath:指定mongo的log日志是哪個揉稚,這里log一定要指定到具體的文件名
--logappend:表示log的寫入是采用附加的方式秒啦,默認(rèn)的是覆蓋之前的文件
&:表示程序在后臺運行
注意:如果是系統(tǒng)非正常關(guān)閉,這樣啟動會報錯搀玖,由于mongodb自動被鎖上了余境,這是需要進入mongodb數(shù)據(jù)庫文件所在的目錄(/var/lib/mongodb/),刪除目錄中的mongodb.lock文件,然后再進行上述操作。
輸入mongo進入shell命令模式芳来,默認(rèn)連接的數(shù)據(jù)庫是test數(shù)據(jù)庫,在此之前一定要確保你已經(jīng)啟動了MongoDB猜拾,否則會出現(xiàn)錯誤即舌,啟動之后運行成功,如下截圖:?
數(shù)據(jù)庫相關(guān)?
show dbs:顯示數(shù)據(jù)庫列表?
show collections:顯示當(dāng)前數(shù)據(jù)庫中的集合(類似關(guān)系數(shù)據(jù)庫中的表table)?
show users:顯示所有用戶?
use yourDB:切換當(dāng)前數(shù)據(jù)庫至yourDB?
db.help()?:顯示數(shù)據(jù)庫操作命令?
db.yourCollection.help()?:顯示集合操作命令挎袜,yourCollection是集合名?
MongoDB沒有創(chuàng)建數(shù)據(jù)庫的命令顽聂,如果你想創(chuàng)建一個“School”的數(shù)據(jù)庫,先運行use School命令盯仪,之后做一些操作(如:創(chuàng)建聚集集合db.createCollection('teacher')),這樣就可以創(chuàng)建一個名叫“School”的數(shù)據(jù)庫紊搪。截圖如下:?
下面以一個School數(shù)據(jù)庫為例,在School數(shù)據(jù)庫中創(chuàng)建兩個集合teacher和student全景,并對student集合中的數(shù)據(jù)進行增刪改查基本操作(集合Collection相當(dāng)于關(guān)系型數(shù)據(jù)庫中的表table)耀石。?
1、切換到School數(shù)據(jù)庫
use School#切換到School數(shù)據(jù)庫爸黄。MongoDB 無需預(yù)創(chuàng)建School數(shù)據(jù)庫滞伟,在使用時會自動創(chuàng)建
2揭鳞、創(chuàng)建Collection
db.createCollection('teacher')#創(chuàng)建一個聚集集合。MongoDB 其實在插入數(shù)據(jù)的時候梆奈,也會自動創(chuàng)建對應(yīng)的集合汹桦,無需預(yù)定義集合
截圖如下:?
3、插入數(shù)據(jù)?
與數(shù)據(jù)庫創(chuàng)建類似鉴裹,插入數(shù)據(jù)時也會自動創(chuàng)建集合舞骆。?
插入數(shù)據(jù)有兩種方式:insert和save。
db.student.insert({_id:1, sname:'zhangsan', sage:20})#_id可選db.student.save({_id:1, sname:'zhangsan', sage:22})#_id可選
這兩種方式径荔,其插入的數(shù)據(jù)中_id字段均可不寫督禽,會自動生成一個唯一的_id來標(biāo)識本條數(shù)據(jù)。而insert和save不同之處在于:在手動插入_id字段時总处,如果_id已經(jīng)存在狈惫,insert不做操作,save做更新操作鹦马;如果不加_id字段胧谈,兩者作用相同都是插入數(shù)據(jù)。截圖如下:?
添加的數(shù)據(jù)其結(jié)構(gòu)是松散的荸频,只要是bson格式均可菱肖,列屬性均不固定,根據(jù)添加的數(shù)據(jù)為準(zhǔn)旭从。先定義數(shù)據(jù)再插入稳强,就可以一次性插入多條數(shù)據(jù),截圖如下:?
運行完以上例子和悦,student 已自動創(chuàng)建退疫,這也說明 MongoDB 不需要預(yù)先定義 collection ,在第一次插入數(shù)據(jù)后鸽素,collection 會自動的創(chuàng)建褒繁。截圖如下:?
3、查找數(shù)據(jù)?
db.youCollection.find(criteria, filterDisplay)?
criteria :查詢條件馍忽,可選?
filterDisplay:篩選顯示部分?jǐn)?shù)據(jù)棒坏,如顯示指定列數(shù)據(jù),可選(當(dāng)選擇時舵匾,第一個參數(shù)不可省略俊抵,若查詢條件為空,可用{}做占位符坐梯,如下例第三句)
db.student.find()#查詢所有記錄徽诲。相當(dāng)于:select * from studentdb.student.find({sname:'lisi'})#查詢sname='lisi'的記錄。相當(dāng)于: select * from student where sname='lisi'db.student.find({},{sname:1, sage:1})#查詢指定列sname、sage數(shù)據(jù)谎替。相當(dāng)于:select sname,sage from student偷溺。sname:1表示返回sname列,默認(rèn)_id字段也是返回的钱贯,可以添加_id:0(意為不返回_id)寫成{sname: 1, sage: 1,_id:0}挫掏,就不會返回默認(rèn)的_id字段了db.student.find({sname:'zhangsan', sage:22})#and 與條件查詢。相當(dāng)于:select * from student where sname = 'zhangsan' and sage = 22db.student.find({$or: [{sage:22}, {sage:25}]})#or 條件查詢秩命。相當(dāng)于:select * from student where sage = 22 or sage = 25
查詢操作類似尉共,這里只給出db.student.find({sname: 'lisi'})查詢的截圖,如下:?
4弃锐、修改數(shù)據(jù)?
db.youCollection.update(criteria, objNew, upsert, multi )?
criteria: update的查詢條件袄友,類似sql update查詢內(nèi)where后面的?
objNew : update的對象和一些更新的操作符(如$set)等,也可以理解為sql update查詢內(nèi)set后面的霹菊。?
upsert : 如果不存在update的記錄剧蚣,是否插入objNew,true為插入旋廷,默認(rèn)是false鸠按,不插入。?
multi: mongodb默認(rèn)是false,只更新找到的第一條記錄饶碘,如果這個參數(shù)為true,就把按條件查出來多條記錄全部更新目尖。默認(rèn)false,只修改匹配到的第一條數(shù)據(jù)熊镣。?
其中criteria和objNew是必選參數(shù)卑雁,upsert和multi可選參數(shù)?
舉例如下:
db.student.update({sname:'lisi'}, {$set: {sage:30}},false,true)#相當(dāng)于:update student set sage =30 where sname = 'lisi';
操作截圖如下:?
5募书、刪除數(shù)據(jù)
db.student.remove({sname:'chenliu'})#相當(dāng)于:delete from student where sname='chenliu'
1
操作截圖如下:?
6绪囱、退出shell命令模式?
輸入exit或者Ctrl+C退出shell命令模式
注意:MongoDB相較安全性更偏向易用性,默認(rèn)是沒有開啟用戶權(quán)限的莹捡,如果想開啟用戶權(quán)限鬼吵,可以參考Ubuntu下開啟MongoDB用戶權(quán)限。
第一步:下載Java MongoDB Driver驅(qū)動jar包篮赢,Java MongoDB Driver下載地址齿椅,默認(rèn)的下載目錄為~/下載或者~/Downloads?
第二步:打開Eclipse,新建Java Project启泣,新建Class涣脚,引入剛剛下載的jar包?
第三步:編碼實現(xiàn)?
下面是源代碼:
importjava.util.ArrayList;importjava.util.List;importorg.bson.Document;importcom.mongodb.MongoClient;importcom.mongodb.client.MongoCollection;importcom.mongodb.client.MongoCursor;importcom.mongodb.client.MongoDatabase;importcom.mongodb.client.model.Filters;publicclassTestMongoDB{/**? ? * @paramargs? ? */publicstaticvoidmain(String[] args) {? ? ? ? insert();//插入數(shù)據(jù)。執(zhí)行插入時寥茫,可將其他三句函數(shù)調(diào)用語句注釋掉遣蚀,下同//? ? ? find(); //查找數(shù)據(jù)//? ? ? update();//更新數(shù)據(jù)//? ? ? delete();//刪除數(shù)據(jù)}/**? ? * 返回指定數(shù)據(jù)庫中的指定集合? ? * @paramdbname 數(shù)據(jù)庫名? ? * @paramcollectionname 集合名? ? * @return*///MongoDB無需預(yù)定義數(shù)據(jù)庫和集合,在使用的時候會自動創(chuàng)建publicstaticMongoCollectiongetCollection(String dbname,String collectionname){//實例化一個mongo客戶端,服務(wù)器地址:localhost(本地),端口號:27017MongoClient? mongoClient=newMongoClient("localhost",27017);//實例化一個mongo數(shù)據(jù)庫MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);//獲取數(shù)據(jù)庫中某個集合MongoCollection collection = mongoDatabase.getCollection(collectionname);returncollection;? ? }/**
? ? * 插入數(shù)據(jù)
? ? */publicstaticvoidinsert(){try{//連接MongoDB,指定連接數(shù)據(jù)庫名芭梯,指定連接表名险耀。MongoCollection collection= getCollection("test","student");//實例化一個文檔,文檔內(nèi)容為{sname:'Mary',sage:25},如果還有其他字段玖喘,可以繼續(xù)追加appendDocument doc1=newDocument("sname","Mary").append("sage",25);//實例化一個文檔,文檔內(nèi)容為{sname:'Bob',sage:20}Document doc2=newDocument("sname","Bob").append("sage",20);? ? ? ? ? ? List documents =newArrayList();//將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() );? ? ? ? }? ? }/**
? ? * 查詢數(shù)據(jù)
? ? */publicstaticvoidfind(){try{? ? ? ? ? ? MongoCollection collection = getCollection("test","student");//通過游標(biāo)遍歷檢索出的文檔集合 //? ? ? ? ? MongoCursor? 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默認(rèn)會顯示)//查詢所有數(shù)據(jù)MongoCursor? cursor= collection.find().iterator();while(cursor.hasNext()){? ? ? ? ? ? ? ? System.out.println(cursor.next().toJson());? ? ? ? ? ? }? ? ? ? }catch(Exception e){? ? ? ? ? ? System.err.println( e.getClass().getName() +": "+ e.getMessage() );? ? ? ? }? ? }/**
? ? * 更新數(shù)據(jù)
? ? */publicstaticvoidupdate(){try{? ? ? ? ? ? MongoCollection collection = getCollection("test","student");//更新文檔? 將文檔中sname='Mary'的文檔修改為sage=22? collection.updateMany(Filters.eq("sname","Mary"),newDocument("$set",newDocument("sage",22)));? ? ? ? ? ? ? System.out.println("更新成功累奈!");? ? ? ? }catch(Exception e){? ? ? ? ? ? System.err.println( e.getClass().getName() +": "+ e.getMessage() );? ? ? ? }? ? }/**
? ? * 刪除數(shù)據(jù)
? ? */publicstaticvoiddelete(){try{? ? ? ? ? ? MongoCollection 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() );? ? ? ? }? ? }}
每次執(zhí)行完程序,都可以返回shell模式查看結(jié)果澎媒。如:在eclipse執(zhí)行完更新操作后赠群,在shell模式輸入db.student.find(),可以查看student集合的所有數(shù)據(jù)旱幼,截圖如下:?